Compare commits
22 Commits
5603858a93
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 2d266a30c2 | |||
| 0d65af4be7 | |||
| fb8f6400be | |||
| 0b7caf6a9f | |||
| 92802d2d50 | |||
| e79e154547 | |||
| 8f502b42b7 | |||
| 3e927f2c6d | |||
| 21be81690f | |||
| 3a301eea2e | |||
| cccafbe651 | |||
| 6264d35a54 | |||
| 9134b28713 | |||
| 5711fb84a8 | |||
| a5e0ae9a0d | |||
| df9dd81487 | |||
| 2b72b6597a | |||
| dba583f1c4 | |||
| b2f92c12f2 | |||
| c4556a9271 | |||
| 3bdbc5ca8c | |||
| 9800abcbc2 |
@@ -1,9 +1,25 @@
|
|||||||
poi/business/*
|
poi/business/*
|
||||||
stat/evaluate/*
|
stat/evaluate/*
|
||||||
stat/community/*
|
stat/community/*
|
||||||
|
stats/evaluate/*
|
||||||
|
stats/community/*
|
||||||
|
stats/aiprice/*
|
||||||
|
stats/cityPrice/*
|
||||||
|
stats/test/*
|
||||||
mt/supply/*
|
mt/supply/*
|
||||||
business/business/*
|
business/business/*
|
||||||
jh/merge/*
|
jh/merge/*
|
||||||
jh/para/*
|
jh/para/*
|
||||||
jh/price/*
|
jh/price/*
|
||||||
|
jh/sample/*
|
||||||
db/*
|
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/*
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
import os
|
||||||
|
import datetime
|
||||||
|
import calendar
|
||||||
|
import json
|
||||||
|
import pandas as pd
|
||||||
|
from goojia_utils import LOG_MONGO_CLIENT
|
||||||
|
from airflow import DAG
|
||||||
|
from airflow.operators.python import PythonOperator
|
||||||
|
from airflow.utils.email import send_email
|
||||||
|
import pendulum
|
||||||
|
|
||||||
|
|
||||||
|
def get_last_month_range(ref_date: datetime.date = None):
|
||||||
|
"""
|
||||||
|
获取参考日期的上个月第一天 00:00:00 与最后一天 23:59:59.999999
|
||||||
|
以北京时间为准
|
||||||
|
"""
|
||||||
|
if ref_date is None:
|
||||||
|
ref_date = datetime.date.today()
|
||||||
|
|
||||||
|
first_day_current_month = ref_date.replace(day=1)
|
||||||
|
last_day_last_month = first_day_current_month - datetime.timedelta(days=1)
|
||||||
|
first_day_last_month = last_day_last_month.replace(day=1)
|
||||||
|
|
||||||
|
start_time = datetime.datetime.combine(first_day_last_month, datetime.time.min)
|
||||||
|
end_time = datetime.datetime.combine(last_day_last_month, datetime.time.max)
|
||||||
|
|
||||||
|
return start_time, end_time, first_day_last_month.year, first_day_last_month.month
|
||||||
|
|
||||||
|
|
||||||
|
def parse_dict(val):
|
||||||
|
"""将字符串类型的 JSON 或字典解析为 dict"""
|
||||||
|
if isinstance(val, dict):
|
||||||
|
return val
|
||||||
|
if isinstance(val, str) and val.strip():
|
||||||
|
try:
|
||||||
|
return json.loads(val)
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
# Excel 中文表头定义:区分【输入】和【输出】
|
||||||
|
EXCEL_COLUMNS = [
|
||||||
|
'请求时间',
|
||||||
|
# 输入参数
|
||||||
|
'输入-城市',
|
||||||
|
'输入-地址',
|
||||||
|
# 响应参数 (取自 res_map.result)
|
||||||
|
'输出-省份',
|
||||||
|
'输出-省份编码',
|
||||||
|
'输出-城市名称',
|
||||||
|
'输出-城市编码',
|
||||||
|
'输出-区域',
|
||||||
|
'输出-区域编码',
|
||||||
|
'输出-乡镇街道',
|
||||||
|
'输出-乡镇街道编码',
|
||||||
|
'输出-是否涉农',
|
||||||
|
'输出-所属区域',
|
||||||
|
'输出-地址验证',
|
||||||
|
'输出-是否为县级市',
|
||||||
|
'输出-是否县城城区',
|
||||||
|
'输出-是否为省国家级开发区',
|
||||||
|
'输出-省国家级开发区名称',
|
||||||
|
'输出-开发区等级'
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def export_and_send_njcb_statement(**context):
|
||||||
|
"""
|
||||||
|
查询上月对公涉农API日志,生成全中文表头Excel对账单并通过邮件发送给顾老师
|
||||||
|
"""
|
||||||
|
now = datetime.datetime.now()
|
||||||
|
start_time, end_time, last_year, last_month = get_last_month_range(now.date())
|
||||||
|
|
||||||
|
print(f"统计时间范围: {start_time} 至 {end_time} (归属年月: {last_year}年{last_month:02d}月)")
|
||||||
|
|
||||||
|
open_uri_log_conn = LOG_MONGO_CLIENT.get_collection('business', 'open_uri_log')
|
||||||
|
|
||||||
|
# 查询条件:
|
||||||
|
# user_id = 1007801, request_uri = /addrSvc/njcbVillageIdentify, c_date在时间范围内, 且只输出code是200的响应
|
||||||
|
query = {
|
||||||
|
'user_id': '1007801',
|
||||||
|
'request_uri': '/addrSvc/njcbVillageIdentify',
|
||||||
|
'c_date': {
|
||||||
|
'$gte': start_time,
|
||||||
|
'$lte': end_time
|
||||||
|
},
|
||||||
|
'$or': [
|
||||||
|
{'code': 200},
|
||||||
|
{'code': '200'}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
print(f"开始查询 MongoDB business.open_uri_log,条件: {query}")
|
||||||
|
cursor = open_uri_log_conn.find(query).batch_size(2000)
|
||||||
|
|
||||||
|
rows = []
|
||||||
|
scanned_count = 0
|
||||||
|
for doc in cursor:
|
||||||
|
scanned_count += 1
|
||||||
|
param_map = parse_dict(doc.get('parameter_map'))
|
||||||
|
res_map = parse_dict(doc.get('res_map'))
|
||||||
|
|
||||||
|
# res_map 结构中有 code, msg, result 嵌套
|
||||||
|
# 实际业务返回字段在 res_map['result'] 中,若无 result 则回退直接使用 res_map
|
||||||
|
result_map = parse_dict(res_map.get('result')) if res_map.get('result') else res_map
|
||||||
|
|
||||||
|
# 过滤只保留"对公涉农"的请求
|
||||||
|
# 涉农类型: 1 对私,2 对公 (默认为对私)
|
||||||
|
req_type = str(param_map.get('type', '1')).strip()
|
||||||
|
if req_type != '2':
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 仅输出"输出-是否涉农"为"农"的部分
|
||||||
|
verify_flag = str(result_map.get('verifyFlag', '')).strip()
|
||||||
|
if verify_flag != '农':
|
||||||
|
continue
|
||||||
|
|
||||||
|
c_date = doc.get('c_date')
|
||||||
|
if isinstance(c_date, datetime.datetime):
|
||||||
|
c_date_str = c_date.strftime('%Y-%m-%d %H:%M:%S')
|
||||||
|
else:
|
||||||
|
c_date_str = str(c_date) if c_date is not None else ''
|
||||||
|
|
||||||
|
row = {
|
||||||
|
'请求时间': c_date_str,
|
||||||
|
# 输入参数
|
||||||
|
'输入-城市': param_map.get('city', ''),
|
||||||
|
'输入-地址': param_map.get('address', ''),
|
||||||
|
# 响应参数 (取自 result_map)
|
||||||
|
'输出-省份': result_map.get('province', ''),
|
||||||
|
'输出-省份编码': result_map.get('provinceCode', ''),
|
||||||
|
'输出-城市名称': result_map.get('city', ''),
|
||||||
|
'输出-城市编码': result_map.get('cityCode', ''),
|
||||||
|
'输出-区域': result_map.get('district', ''),
|
||||||
|
'输出-区域编码': result_map.get('districtCode', ''),
|
||||||
|
'输出-乡镇街道': result_map.get('town', ''),
|
||||||
|
'输出-乡镇街道编码': result_map.get('townCode', ''),
|
||||||
|
'输出-是否涉农': verify_flag,
|
||||||
|
'输出-所属区域': result_map.get('addrArea', ''),
|
||||||
|
'输出-地址验证': result_map.get('addrVerify', ''),
|
||||||
|
'输出-是否为县级市': result_map.get('countyLevelCity', ''),
|
||||||
|
'输出-是否县城城区': result_map.get('countyGov', ''),
|
||||||
|
'输出-是否为省国家级开发区': result_map.get('devDistrict', ''),
|
||||||
|
'输出-省国家级开发区名称': result_map.get('devDistrictName', ''),
|
||||||
|
'输出-开发区等级': result_map.get('devLevel', '')
|
||||||
|
}
|
||||||
|
rows.append(row)
|
||||||
|
|
||||||
|
total_count = len(rows)
|
||||||
|
print(f"扫描命中记录: {scanned_count} 条,其中符合对公且是否涉农为'农'的记录: {total_count} 条")
|
||||||
|
|
||||||
|
# 生成 Excel 文件
|
||||||
|
tmp_dir = os.path.join(os.path.expanduser('~'), 'tmp', 'njcb_statement')
|
||||||
|
os.makedirs(tmp_dir, exist_ok=True)
|
||||||
|
filename = f"南京银行涉农API对公涉农调用流水_{last_year}{last_month:02d}.xlsx"
|
||||||
|
excel_path = os.path.join(tmp_dir, filename)
|
||||||
|
|
||||||
|
if rows:
|
||||||
|
df = pd.DataFrame(rows, columns=EXCEL_COLUMNS)
|
||||||
|
else:
|
||||||
|
df = pd.DataFrame(columns=EXCEL_COLUMNS)
|
||||||
|
|
||||||
|
df.to_excel(excel_path, index=False, engine='openpyxl')
|
||||||
|
print(f"Excel文件生成成功: {excel_path}")
|
||||||
|
|
||||||
|
# 发送邮件
|
||||||
|
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>
|
||||||
|
<p>您好!</p>
|
||||||
|
<p>附件为南京银行 <b>{last_year}年{last_month:02d}月</b> 涉农识别API(/addrSvc/njcbVillageIdentify)对公涉农调用流水,请查收。</p>
|
||||||
|
<ul>
|
||||||
|
<li><b>对账周期:</b> {start_time.strftime('%Y-%m-%d')} 至 {end_time.strftime('%Y-%m-%d')}</li>
|
||||||
|
<li><b>调用有效成功条数(Code=200 且 对公且判定为农):</b> {total_count} 条</li>
|
||||||
|
</ul>
|
||||||
|
<p>如有任何疑问,请随时与我们联系。</p>
|
||||||
|
"""
|
||||||
|
|
||||||
|
print(f"正在发送邮件至: {receiver}, 抄送: {cc_receiver}, 附件: {excel_path}")
|
||||||
|
send_email(
|
||||||
|
to=receiver,
|
||||||
|
subject=subject,
|
||||||
|
html_content=html_content,
|
||||||
|
files=[excel_path],
|
||||||
|
cc=cc_receiver
|
||||||
|
)
|
||||||
|
print("邮件发送完成。")
|
||||||
|
|
||||||
|
|
||||||
|
# Airflow DAG 定义:每月2号上午9:00执行(北京时间)
|
||||||
|
with DAG(
|
||||||
|
dag_id="njcb_village_identify_statement_dag",
|
||||||
|
schedule="0 9 2 * *",
|
||||||
|
start_date=pendulum.datetime(2024, 1, 1, tz="Asia/Shanghai"),
|
||||||
|
catchup=False,
|
||||||
|
description="每月2号给南京银行顾老师发送上个月涉农API对公涉农调用流水",
|
||||||
|
tags=["api", "njcb", "statement"]
|
||||||
|
) as dag:
|
||||||
|
|
||||||
|
send_statement_task = PythonOperator(
|
||||||
|
task_id="send_njcb_village_statement",
|
||||||
|
python_callable=export_and_send_njcb_statement
|
||||||
|
)
|
||||||
@@ -1,6 +1,13 @@
|
|||||||
"""
|
"""
|
||||||
同步小区基本信息至ES206
|
同步小区基本信息至ES206
|
||||||
"""
|
"""
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
# 强制设置 Python 进程内部本地时区为北京时间(CST / UTC+8),消除 Docker 容器内的 UTC 时区日志差异
|
||||||
|
os.environ['TZ'] = 'Asia/Shanghai'
|
||||||
|
if hasattr(time, 'tzset'):
|
||||||
|
time.tzset()
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|||||||
@@ -109,7 +109,7 @@ def sync_data(target_month=None):
|
|||||||
date_filter = f"and m_date >= '{three_months_ago}'"
|
date_filter = f"and m_date >= '{three_months_ago}'"
|
||||||
log.info(f"增量运行,过滤近3个月内有更新的数据 (m_date >= '{three_months_ago}')")
|
log.info(f"增量运行,过滤近3个月内有更新的数据 (m_date >= '{three_months_ago}')")
|
||||||
|
|
||||||
sql = f"select city, region, name, avg_price, root, m_date from {index_name} where avg_price is not null {date_filter}"
|
sql = f"select city, region, name, avg_price, root, m_date from {index_name} where avg_price is not null and avg_price > 0 {date_filter}"
|
||||||
|
|
||||||
# 城市手动过滤(可选,通过外部参数调度)
|
# 城市手动过滤(可选,通过外部参数调度)
|
||||||
sys_city = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].isdigit() else None
|
sys_city = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].isdigit() else None
|
||||||
@@ -138,6 +138,15 @@ def sync_data(target_month=None):
|
|||||||
if pd.isna(city) or pd.isna(region) or pd.isna(name) or pd.isna(avg_price) or pd.isna(root):
|
if pd.isna(city) or pd.isna(region) or pd.isna(name) or pd.isna(avg_price) or pd.isna(root):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
price_val = int(float(avg_price))
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 过滤价格 <= 0 的异常/无效数据
|
||||||
|
if price_val <= 0:
|
||||||
|
continue
|
||||||
|
|
||||||
s_date = parse_s_date(m_date)
|
s_date = parse_s_date(m_date)
|
||||||
if s_date is None:
|
if s_date is None:
|
||||||
continue
|
continue
|
||||||
@@ -155,7 +164,6 @@ def sync_data(target_month=None):
|
|||||||
grouped[key] = {}
|
grouped[key] = {}
|
||||||
|
|
||||||
# 多个相同 root 冲突时,此处保留最新或较高价格(以整型存储)
|
# 多个相同 root 冲突时,此处保留最新或较高价格(以整型存储)
|
||||||
price_val = int(float(avg_price))
|
|
||||||
current_val = grouped[key].get(field_name)
|
current_val = grouped[key].get(field_name)
|
||||||
if current_val is None or price_val > current_val:
|
if current_val is None or price_val > current_val:
|
||||||
grouped[key][field_name] = price_val
|
grouped[key][field_name] = price_val
|
||||||
|
|||||||
@@ -9,16 +9,8 @@ from goojia_utils import DIDATA_DEV_ELASTIC_CLIENT, threads, geohashutils, areau
|
|||||||
import pandas as pd
|
import pandas as pd
|
||||||
from elasticsearch import helpers
|
from elasticsearch import helpers
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
# 🛡️ 2. 终极绝招:利用 Elasticsearch 8.x 官方 options() 机制,强行生成一个无 compatible 请求头的底层客户端并覆盖,彻底降维打击 406 报错!
|
|
||||||
if hasattr(DIDATA_DEV_ELASTIC_CLIENT.elastic_client, 'options'):
|
|
||||||
DIDATA_DEV_ELASTIC_CLIENT.elastic_client = DIDATA_DEV_ELASTIC_CLIENT.elastic_client.options(
|
|
||||||
headers={"content-type": "application/json", "accept": "application/json"}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# ================== 🛡️ 安全运行入口 ==================
|
# ================== 🛡️ 安全运行入口 ==================
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -3,11 +3,15 @@
|
|||||||
"""
|
"""
|
||||||
from airflow.providers.standard.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
from airflow.operators.python import PythonOperator, BranchPythonOperator
|
from airflow.operators.python import PythonOperator, BranchPythonOperator
|
||||||
from office.rent.base_price import calc
|
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|
||||||
|
def run_base_rent_calc(**kwargs):
|
||||||
|
from office.rent.base_price import calc
|
||||||
|
return calc(**kwargs)
|
||||||
|
|
||||||
|
|
||||||
def choose_task(**context):
|
def choose_task(**context):
|
||||||
"""根据 dag_run.conf 决定执行哪个任务"""
|
"""根据 dag_run.conf 决定执行哪个任务"""
|
||||||
conf = context['dag_run'].conf or {}
|
conf = context['dag_run'].conf or {}
|
||||||
@@ -50,7 +54,7 @@ with DAG(
|
|||||||
# 任务2:写字楼租金计算
|
# 任务2:写字楼租金计算
|
||||||
t2 = PythonOperator(
|
t2 = PythonOperator(
|
||||||
task_id='office_base_rent_calc',
|
task_id='office_base_rent_calc',
|
||||||
python_callable=calc,
|
python_callable=run_base_rent_calc,
|
||||||
# 🛡️ 已移除 provide_context=True,防止 Airflow 3.3.0 报错崩溃
|
# 🛡️ 已移除 provide_context=True,防止 Airflow 3.3.0 报错崩溃
|
||||||
)
|
)
|
||||||
branch_task >> [t1, t2]
|
branch_task >> [t1, t2]
|
||||||
@@ -1,13 +1,21 @@
|
|||||||
from airflow.providers.standard.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
from airflow.operators.python import PythonOperator, BranchPythonOperator
|
from airflow.operators.python import PythonOperator, BranchPythonOperator
|
||||||
from airflow.operators.empty import EmptyOperator
|
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
|
import pendulum
|
||||||
|
|
||||||
from airflow import DAG
|
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):
|
def choose_task(**context):
|
||||||
"""根据 dag_run.conf 决定执行哪个任务"""
|
"""根据 dag_run.conf 决定执行哪个任务"""
|
||||||
conf = context['dag_run'].conf or {}
|
conf = context['dag_run'].conf or {}
|
||||||
@@ -56,14 +64,14 @@ with DAG(
|
|||||||
# 任务1: 写字楼出售基础价格计算
|
# 任务1: 写字楼出售基础价格计算
|
||||||
t1 = PythonOperator(
|
t1 = PythonOperator(
|
||||||
task_id='office_sell_base_price_calc',
|
task_id='office_sell_base_price_calc',
|
||||||
python_callable=calc,
|
python_callable=run_base_price_calc,
|
||||||
# 🛡️ 已安全移除 provide_context=True
|
# 🛡️ 已安全移除 provide_context=True
|
||||||
)
|
)
|
||||||
|
|
||||||
# 任务2: 无样本写字楼出售基础价格填充
|
# 任务2: 无样本写字楼出售基础价格填充
|
||||||
t2 = PythonOperator(
|
t2 = PythonOperator(
|
||||||
task_id='office_no_sample_sell_base_price_calc',
|
task_id='office_no_sample_sell_base_price_calc',
|
||||||
python_callable=fill_base_price,
|
python_callable=run_fill_base_price,
|
||||||
# 🛡️ 已安全移除 provide_context=True
|
# 🛡️ 已安全移除 provide_context=True
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ def calcByOffice(city, district, office_name):
|
|||||||
# 只查询该小区的样本
|
# 只查询该小区的样本
|
||||||
year_time = dateutils.format_date(dateutils.datetime.datetime.now())
|
year_time = dateutils.format_date(dateutils.datetime.datetime.now())
|
||||||
one_year_time = dateutils.format_date(dateutils.add_months(dateutils.datetime.datetime.now(), days=-365))
|
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)
|
sample = es.scan_by_sql_to_data_frame(sql)
|
||||||
|
|
||||||
location = {
|
location = {
|
||||||
@@ -114,7 +114,7 @@ def calcByOffice(city, district, office_name):
|
|||||||
new_avg_price = round(average_price, 2)
|
new_avg_price = round(average_price, 2)
|
||||||
elif len(sample) > 0:
|
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):
|
if pd.notna(new_avg_price):
|
||||||
action = UpdateOne(
|
action = UpdateOne(
|
||||||
{'cat': 'office', 'city': city, 'district': district, 'name': office_name, 'date': curr_date},
|
{'cat': 'office', 'city': city, 'district': district, 'name': office_name, 'date': curr_date},
|
||||||
@@ -127,12 +127,113 @@ def calcByOffice(city, district, office_name):
|
|||||||
upsert=True)
|
upsert=True)
|
||||||
office_rent_stat_conn.bulk_write([action])
|
office_rent_stat_conn.bulk_write([action])
|
||||||
|
|
||||||
|
# 🏁 触发 MoM 和 YoY(环比与同比)的自动计算与更新
|
||||||
|
calculate_mom_yoy_for_office(city, district, office_name)
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_mom_yoy_for_office(city, district, office_name):
|
||||||
|
"""
|
||||||
|
计算特定写字楼历史所有月份的 mom (环比) 和 yoy (同比) 并更新
|
||||||
|
"""
|
||||||
|
query = {
|
||||||
|
'cat': 'office',
|
||||||
|
'city': city,
|
||||||
|
'district': district,
|
||||||
|
'name': office_name
|
||||||
|
}
|
||||||
|
docs = list(office_rent_stat_conn.find(query).sort('date', 1))
|
||||||
|
if not docs:
|
||||||
|
return
|
||||||
|
|
||||||
|
doc_dict = {doc['date']: doc for doc in docs}
|
||||||
|
actions = []
|
||||||
|
for doc in docs:
|
||||||
|
curr_date = doc['date']
|
||||||
|
curr_price = doc.get('avg_price')
|
||||||
|
if not curr_price:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 计算前一个月的 YYYYMM
|
||||||
|
year = curr_date // 100
|
||||||
|
month = curr_date % 100
|
||||||
|
if month == 1:
|
||||||
|
prev_date = (year - 1) * 100 + 12
|
||||||
|
else:
|
||||||
|
prev_date = curr_date - 1
|
||||||
|
|
||||||
|
# 计算上年同月的 YYYYMM
|
||||||
|
ly_date = curr_date - 100
|
||||||
|
|
||||||
|
# 计算 mom (环比)
|
||||||
|
mom = None
|
||||||
|
if prev_date in doc_dict and doc_dict[prev_date].get('avg_price'):
|
||||||
|
prev_price = doc_dict[prev_date]['avg_price']
|
||||||
|
mom = round((curr_price - prev_price) / prev_price * 100, 2)
|
||||||
|
|
||||||
|
# 计算 yoy (同比)
|
||||||
|
yoy = None
|
||||||
|
if ly_date in doc_dict and doc_dict[ly_date].get('avg_price'):
|
||||||
|
ly_price = doc_dict[ly_date]['avg_price']
|
||||||
|
yoy = round((curr_price - ly_price) / ly_price * 100, 2)
|
||||||
|
|
||||||
|
action = UpdateOne(
|
||||||
|
{'_id': doc['_id']},
|
||||||
|
{'$set': {'mom': mom, 'yoy': yoy}}
|
||||||
|
)
|
||||||
|
actions.append(action)
|
||||||
|
|
||||||
|
if actions:
|
||||||
|
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):
|
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):
|
if pd.notna(city):
|
||||||
sql += "and city='" + city + "' "
|
sql += "and city='" + city + "' "
|
||||||
if pd.notna(year_month):
|
if pd.notna(year_month):
|
||||||
@@ -154,9 +255,11 @@ def calcByCity(city, year_month):
|
|||||||
office = getOffice(city)
|
office = getOffice(city)
|
||||||
|
|
||||||
update_office(city, office, sample, year_month)
|
update_office(city, office, sample, year_month)
|
||||||
|
calculate_mom_yoy_by_month(year_month, city)
|
||||||
|
|
||||||
|
|
||||||
def update_office(city, office, sample, year_month):
|
def update_office(city, office, sample, year_month):
|
||||||
|
target_city = city
|
||||||
if 'bed_kind' not in office.columns:
|
if 'bed_kind' not in office.columns:
|
||||||
office['bed_kind'] = None
|
office['bed_kind'] = None
|
||||||
if 'estate_type2' not in office.columns:
|
if 'estate_type2' not in office.columns:
|
||||||
@@ -385,8 +488,8 @@ def update_office(city, office, sample, year_month):
|
|||||||
actions.clear()
|
actions.clear()
|
||||||
# 第五步
|
# 第五步
|
||||||
query = {'cat': 'office', 'date': year_month, 'calc_type': {'$in': [1, 2, 3]}}
|
query = {'cat': 'office', 'date': year_month, 'calc_type': {'$in': [1, 2, 3]}}
|
||||||
if pd.notna(city):
|
if pd.notna(target_city) and target_city != '':
|
||||||
query['city'] = city
|
query['city'] = target_city
|
||||||
db_df = pd.DataFrame(list(office_rent_stat_conn.find(query)))
|
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(
|
office_info = office[['city', 'region', 'name', 'lng', 'lat', 'estate_type2', 'bed_kind']].drop_duplicates(
|
||||||
keep='first')
|
keep='first')
|
||||||
|
|||||||
+47
-20
@@ -18,7 +18,7 @@ def calc(city, year_month):
|
|||||||
raise Exception('年月格式错误yyyyMM')
|
raise Exception('年月格式错误yyyyMM')
|
||||||
office = es_client.scan_by_sql_to_data_frame(
|
office = es_client.scan_by_sql_to_data_frame(
|
||||||
"select * from latest_seawater where cat='office_rent' and city='" + city + "' and p_date>=" + str(
|
"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:
|
if len(office) > 0:
|
||||||
office['day_avg_price'] = office['avg_price'] / 30
|
office['day_avg_price'] = office['avg_price'] / 30
|
||||||
# 计算总价的Z-score
|
# 计算总价的Z-score
|
||||||
@@ -37,22 +37,36 @@ def calc(city, year_month):
|
|||||||
region_median_count_prices = {'median': {}, 'count': {}}
|
region_median_count_prices = {'median': {}, 'count': {}}
|
||||||
|
|
||||||
actions = list()
|
actions = list()
|
||||||
|
year_month = int(year_month)
|
||||||
last_month = int(
|
last_month = int(
|
||||||
dateutils.format_date(dateutils.add_months(dateutils.parse_date(str(year_month), '%Y%m'), months=-1), '%Y%m'))
|
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):
|
if pd.isna(city_price):
|
||||||
# 处理均价为空情况,用上月均价替代
|
# 处理均价为空情况,用上月均价替代
|
||||||
stat = office_rent_stat_conn.find_one({'city': city, 'cat': 'city', 'date': int(last_month)})
|
if pd.isna(prev_city_stat):
|
||||||
if pd.isna(stat):
|
|
||||||
return False
|
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):
|
if pd.isna(last_month_city_price):
|
||||||
return False
|
return False
|
||||||
city_price = last_month_city_price
|
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
|
# 写入MONGODB
|
||||||
action = UpdateOne({'city': city, 'cat': 'city', 'date': int(year_month)},
|
action = UpdateOne({'city': city, 'cat': 'city', 'date': int(year_month)},
|
||||||
{'$set': {'city': city, 'cat': 'city', 'date': int(year_month), 'avg_price': city_price,
|
{'$set': {'city': city, 'cat': 'city', 'date': int(year_month), 'avg_price': city_price,
|
||||||
|
'mom': city_mom, 'yoy': city_yoy,
|
||||||
'updated_date': datetime.now()}},
|
'updated_date': datetime.now()}},
|
||||||
upsert=True)
|
upsert=True)
|
||||||
|
|
||||||
@@ -60,37 +74,50 @@ def calc(city, year_month):
|
|||||||
for region in areautils.get_all_districts(city):
|
for region in areautils.get_all_districts(city):
|
||||||
region_avg_prices = region_median_count_prices['median']
|
region_avg_prices = region_median_count_prices['median']
|
||||||
region_count = region_median_count_prices['count']
|
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:
|
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:
|
else:
|
||||||
# 处理均价为空情况,用上月均价替代
|
# 处理均价为空情况,用上月均价替代
|
||||||
district_stat = office_rent_stat_conn.find_one({'city': city, 'cat': 'district', 'date': int(last_month), 'district': region})
|
if pd.isna(prev_district_stat):
|
||||||
if pd.isna(district_stat):
|
|
||||||
continue
|
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):
|
if pd.isna(last_month_region_price):
|
||||||
continue
|
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},
|
action = UpdateOne({'city': city, 'cat': 'district', 'date': int(year_month), 'district': region},
|
||||||
{'$set': {'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)
|
upsert=True)
|
||||||
actions.append(action)
|
actions.append(action)
|
||||||
office_rent_stat_conn.bulk_write(actions)
|
office_rent_stat_conn.bulk_write(actions)
|
||||||
log.info(f"{city} {year_month} 均价计算完毕!")
|
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 == '':
|
if yearmonth == '':
|
||||||
date = dateutils.add_months(datetime.today(), months=-1)
|
date = dateutils.add_months(datetime.today(), months=-1)
|
||||||
yearmonth = int(dateutils.format_date(date, '%Y%m'))
|
yearmonth = int(dateutils.format_date(date, '%Y%m'))
|
||||||
try:
|
try:
|
||||||
for city in areautils.get_all_cities():
|
for city in areautils.get_all_cities():
|
||||||
calc(city, yearmonth)
|
calc(city, yearmonth)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.error(e)
|
log.error(e)
|
||||||
|
|
||||||
# # 初始化从2024年9月
|
# # 初始化从2024年9月
|
||||||
# 创建从2024年9月到2024年12月的日期范围
|
# 创建从2024年9月到2024年12月的日期范围
|
||||||
|
|||||||
@@ -128,6 +128,107 @@ def calcByOffice(city, district, office_name):
|
|||||||
upsert=True)
|
upsert=True)
|
||||||
office_sell_stat_conn.bulk_write([action])
|
office_sell_stat_conn.bulk_write([action])
|
||||||
|
|
||||||
|
# 🏁 触发 MoM 和 YoY(环比与同比)的自动计算与更新(出售)
|
||||||
|
calculate_mom_yoy_for_office(city, district, office_name)
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_mom_yoy_for_office(city, district, office_name):
|
||||||
|
"""
|
||||||
|
计算特定写字楼出售历史所有月份的 mom (环比) 和 yoy (同比) 并更新
|
||||||
|
"""
|
||||||
|
query = {
|
||||||
|
'cat': 'office',
|
||||||
|
'city': city,
|
||||||
|
'district': district,
|
||||||
|
'name': office_name
|
||||||
|
}
|
||||||
|
docs = list(office_sell_stat_conn.find(query).sort('date', 1))
|
||||||
|
if not docs:
|
||||||
|
return
|
||||||
|
|
||||||
|
doc_dict = {doc['date']: doc for doc in docs}
|
||||||
|
actions = []
|
||||||
|
for doc in docs:
|
||||||
|
curr_date = doc['date']
|
||||||
|
curr_price = doc.get('avg_price')
|
||||||
|
if not curr_price:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 计算前一个月的 YYYYMM
|
||||||
|
year = curr_date // 100
|
||||||
|
month = curr_date % 100
|
||||||
|
if month == 1:
|
||||||
|
prev_date = (year - 1) * 100 + 12
|
||||||
|
else:
|
||||||
|
prev_date = curr_date - 1
|
||||||
|
|
||||||
|
# 计算上年同月的 YYYYMM
|
||||||
|
ly_date = curr_date - 100
|
||||||
|
|
||||||
|
# 计算 mom (环比)
|
||||||
|
mom = None
|
||||||
|
if prev_date in doc_dict and doc_dict[prev_date].get('avg_price'):
|
||||||
|
prev_price = doc_dict[prev_date]['avg_price']
|
||||||
|
mom = round((curr_price - prev_price) / prev_price * 100, 2)
|
||||||
|
|
||||||
|
# 计算 yoy (同比)
|
||||||
|
yoy = None
|
||||||
|
if ly_date in doc_dict and doc_dict[ly_date].get('avg_price'):
|
||||||
|
ly_price = doc_dict[ly_date]['avg_price']
|
||||||
|
yoy = round((curr_price - ly_price) / ly_price * 100, 2)
|
||||||
|
|
||||||
|
action = UpdateOne(
|
||||||
|
{'_id': doc['_id']},
|
||||||
|
{'$set': {'mom': mom, 'yoy': yoy}}
|
||||||
|
)
|
||||||
|
actions.append(action)
|
||||||
|
|
||||||
|
if actions:
|
||||||
|
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):
|
def calcByCity(city, year_month):
|
||||||
"""
|
"""
|
||||||
@@ -156,9 +257,11 @@ def calcByCity(city, year_month):
|
|||||||
office = getOffice(city)
|
office = getOffice(city)
|
||||||
|
|
||||||
update_office(city, office, sample, year_month)
|
update_office(city, office, sample, year_month)
|
||||||
|
calculate_mom_yoy_by_month(year_month, city)
|
||||||
|
|
||||||
|
|
||||||
def update_office(city, office, sample, year_month):
|
def update_office(city, office, sample, year_month):
|
||||||
|
target_city = city
|
||||||
if 'bed_kind' not in office.columns:
|
if 'bed_kind' not in office.columns:
|
||||||
office['bed_kind'] = None
|
office['bed_kind'] = None
|
||||||
if 'estate_type2' not in office.columns:
|
if 'estate_type2' not in office.columns:
|
||||||
@@ -388,8 +491,8 @@ def update_office(city, office, sample, year_month):
|
|||||||
actions.clear()
|
actions.clear()
|
||||||
# 第五步
|
# 第五步
|
||||||
query = {'cat': 'office', 'date': year_month, 'calc_type': {'$in': [1, 2, 3]}}
|
query = {'cat': 'office', 'date': year_month, 'calc_type': {'$in': [1, 2, 3]}}
|
||||||
if pd.notna(city):
|
if pd.notna(target_city) and target_city != '':
|
||||||
query['city'] = city
|
query['city'] = target_city
|
||||||
db_df = pd.DataFrame(list(office_sell_stat_conn.find(query)))
|
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(
|
office_info = office[['city', 'region', 'name', 'lng', 'lat', 'estate_type2', 'bed_kind']].drop_duplicates(
|
||||||
keep='first')
|
keep='first')
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
from goojia_utils import DIDATA_DEV_ELASTIC_CLIENT, dateutils, MAIN_MONGO_CLIENT, threads, areautils
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pymongo import UpdateOne
|
from pymongo import UpdateOne
|
||||||
import logging
|
import logging
|
||||||
import sys
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
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):
|
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 获取参数
|
# 从 Airflow 的 dag_run.conf 获取参数
|
||||||
conf = kwargs.get('dag_run').conf if kwargs.get('dag_run') else {}
|
conf = kwargs.get('dag_run').conf if kwargs.get('dag_run') else {}
|
||||||
city = conf.get('city', '')
|
city = conf.get('city', '')
|
||||||
@@ -38,12 +38,16 @@ def fill_base_price(**kwargs):
|
|||||||
if len(office_rent) <= 0:
|
if len(office_rent) <= 0:
|
||||||
return
|
return
|
||||||
if year_month != '':
|
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:
|
else:
|
||||||
# 对于单个重算的不进行补充,已经自己补充过了
|
# 对于单个重算的不进行补充,已经自己补充过了
|
||||||
pass
|
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[['city', 'district', 'name', 'avg_price']]
|
||||||
office_sell_df = office_sell_df.rename(columns={'avg_price': 'sell_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']]
|
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 = threads.process_dataframe_multithread(merge2_df, deal, 10)
|
||||||
merge2_df = merge2_df[merge2_df['sell_price'].notna()]
|
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()
|
actions = list()
|
||||||
count = 0
|
count = 0
|
||||||
for index, row in merge2_df.iterrows():
|
for index, row in merge2_df.iterrows():
|
||||||
curr_city = row['city']
|
curr_city = row['city']
|
||||||
region = row['district']
|
region = row['district']
|
||||||
name = row['name']
|
name = row['name']
|
||||||
sell_price = row['sell_price']
|
sell_price = int(row['sell_price'])
|
||||||
estate_type2 = row['estate_type2']
|
estate_type2 = row['estate_type2']
|
||||||
bed_kind = row['bed_kind']
|
bed_kind = row['bed_kind']
|
||||||
location = row['location']
|
location = row['location']
|
||||||
action = UpdateOne({'cat': 'office', 'city': curr_city, 'district': region, 'name': name, 'date': year_month},
|
prev_p = prev_map.get((curr_city, region, name))
|
||||||
{'$set': {'city': curr_city, 'cat': 'office', 'date': year_month, 'district': region,
|
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,
|
'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,
|
'location': location,
|
||||||
'calc_type': 5, 'updated_date': datetime.now()}},
|
'calc_type': 5, 'updated_date': datetime.now()}},
|
||||||
upsert=True)
|
upsert=True)
|
||||||
|
|||||||
@@ -59,11 +59,25 @@ def calc(city, year_month):
|
|||||||
merge2_df = threads.process_dataframe_multithread(merge2_df, deal_city, 10)
|
merge2_df = threads.process_dataframe_multithread(merge2_df, deal_city, 10)
|
||||||
merge2_df = merge2_df[merge2_df['sell_price'].notna()]
|
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()
|
actions = list()
|
||||||
# 写入MONGODB
|
# 写入MONGODB
|
||||||
for index, row in merge2_df.iterrows():
|
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},
|
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()}},
|
'updated_date': datetime.now()}},
|
||||||
upsert=True)
|
upsert=True)
|
||||||
actions.append(action)
|
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 = threads.process_dataframe_multithread(merge2_df, deal_district, 10)
|
||||||
merge2_df = merge2_df[merge2_df['sell_price'].notna()]
|
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
|
# 写入MONGODB
|
||||||
for index, row in merge2_df.iterrows():
|
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},
|
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()}},
|
'updated_date': datetime.now()}},
|
||||||
upsert=True)
|
upsert=True)
|
||||||
actions.append(action)
|
actions.append(action)
|
||||||
@@ -101,17 +124,18 @@ def calc(city, year_month):
|
|||||||
log.info(f"均价补充完毕!")
|
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 == '':
|
if yearmonth == '':
|
||||||
date = dateutils.add_months(datetime.today(), months=-1)
|
date = dateutils.add_months(datetime.today(), months=-1)
|
||||||
yearmonth = int(dateutils.format_date(date, '%Y%m'))
|
yearmonth = int(dateutils.format_date(date, '%Y%m'))
|
||||||
try:
|
try:
|
||||||
if type(yearmonth) is str:
|
if type(yearmonth) is str:
|
||||||
yearmonth = int(yearmonth)
|
yearmonth = int(yearmonth)
|
||||||
calc(None, yearmonth)
|
calc(None, yearmonth)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.error(e)
|
log.error(e)
|
||||||
|
|
||||||
# # 初始化从2024年9月
|
# # 初始化从2024年9月
|
||||||
# 创建从2024年9月到2024年12月的日期范围
|
# 创建从2024年9月到2024年12月的日期范围
|
||||||
|
|||||||
+51
-22
@@ -37,22 +37,38 @@ def calc(city, year_month):
|
|||||||
region_median_count_prices = {'median': {}, 'count': {}}
|
region_median_count_prices = {'median': {}, 'count': {}}
|
||||||
|
|
||||||
actions = list()
|
actions = list()
|
||||||
|
year_month = int(year_month)
|
||||||
last_month = int(
|
last_month = int(
|
||||||
dateutils.format_date(dateutils.add_months(dateutils.parse_date(str(year_month), '%Y%m'), months=-1), '%Y%m'))
|
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):
|
if pd.isna(city_price):
|
||||||
# 处理均价为空情况,用上月均价替代
|
# 处理均价为空情况,用上月均价替代
|
||||||
stat = office_sell_stat_conn.find_one({'city': city, 'cat': 'city', 'date': last_month})
|
if pd.isna(prev_city_stat):
|
||||||
if pd.isna(stat):
|
|
||||||
return False
|
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):
|
if pd.isna(last_month_city_price):
|
||||||
return False
|
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
|
# 写入MONGODB
|
||||||
action = UpdateOne({'city': city, 'cat': 'city', 'date': year_month},
|
action = UpdateOne({'city': city, 'cat': 'city', 'date': year_month},
|
||||||
{'$set': {'city': city, 'cat': 'city', 'date': year_month, 'avg_price': int(city_price),
|
{'$set': {'city': city, 'cat': 'city', 'date': year_month, 'avg_price': int(city_price),
|
||||||
|
'mom': city_mom, 'yoy': city_yoy,
|
||||||
'updated_date': datetime.now()}},
|
'updated_date': datetime.now()}},
|
||||||
upsert=True)
|
upsert=True)
|
||||||
|
|
||||||
@@ -60,38 +76,51 @@ def calc(city, year_month):
|
|||||||
for region in areautils.get_all_districts(city):
|
for region in areautils.get_all_districts(city):
|
||||||
region_avg_prices = region_median_count_prices['median']
|
region_avg_prices = region_median_count_prices['median']
|
||||||
region_count = region_median_count_prices['count']
|
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:
|
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:
|
else:
|
||||||
# 处理均价为空情况,用上月均价替代
|
# 处理均价为空情况,用上月均价替代
|
||||||
district_stat = office_sell_stat_conn.find_one({'city': city, 'cat': 'district', 'date': last_month, 'district': region})
|
if pd.isna(prev_district_stat):
|
||||||
if pd.isna(district_stat):
|
|
||||||
continue
|
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):
|
if pd.isna(last_month_region_price):
|
||||||
continue
|
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},
|
action = UpdateOne({'city': city, 'cat': 'district', 'date': year_month, 'district': region},
|
||||||
{'$set': {'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)
|
upsert=True)
|
||||||
actions.append(action)
|
actions.append(action)
|
||||||
office_sell_stat_conn.bulk_write(actions)
|
office_sell_stat_conn.bulk_write(actions)
|
||||||
log.info(f"{city} {year_month} 均价计算完毕!")
|
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 == '':
|
if yearmonth == '':
|
||||||
date = dateutils.add_months(datetime.today(), months=-1)
|
date = dateutils.add_months(datetime.today(), months=-1)
|
||||||
yearmonth = int(dateutils.format_date(date, '%Y%m'))
|
yearmonth = int(dateutils.format_date(date, '%Y%m'))
|
||||||
try:
|
try:
|
||||||
if type(yearmonth) is str:
|
if type(yearmonth) is str:
|
||||||
yearmonth = int(yearmonth)
|
yearmonth = int(yearmonth)
|
||||||
for city in areautils.get_all_cities():
|
for city in areautils.get_all_cities():
|
||||||
calc(city, yearmonth)
|
calc(city, yearmonth)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.error(e)
|
log.error(e)
|
||||||
|
|
||||||
# # 初始化从2024年9月
|
# # 初始化从2024年9月
|
||||||
# 创建从2024年9月到2024年12月的日期范围
|
# 创建从2024年9月到2024年12月的日期范围
|
||||||
|
|||||||
@@ -0,0 +1,327 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
县政府所在乡镇街道核验排查定时任务
|
||||||
|
每月1日9点运行,比对 ES administrative_mapping_45 索引中县政府所在街道与高德逆地理街道并发送审核邮件
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import requests
|
||||||
|
import pandas as pd
|
||||||
|
from datetime import datetime
|
||||||
|
from goojia_utils import ElasticSearchClient
|
||||||
|
from airflow import DAG
|
||||||
|
from airflow.operators.python import PythonOperator
|
||||||
|
from airflow.utils.email import send_email
|
||||||
|
import pendulum
|
||||||
|
|
||||||
|
# 高德 Web 服务 API Key
|
||||||
|
AMAP_KEY = "a34894d151fffff94f9a33bae3d5565c"
|
||||||
|
INDEX_NAME = "administrative_mapping_45"
|
||||||
|
ES_HOST = "192.168.0.206"
|
||||||
|
|
||||||
|
|
||||||
|
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 = {
|
||||||
|
"key": key,
|
||||||
|
"location": f"{lon},{lat}",
|
||||||
|
"extensions": "base",
|
||||||
|
"roadlevel": 0
|
||||||
|
}
|
||||||
|
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":
|
||||||
|
regeocode = data.get("regeocode", {})
|
||||||
|
addr_comp = regeocode.get("addressComponent", {})
|
||||||
|
township = addr_comp.get("township")
|
||||||
|
if isinstance(township, str):
|
||||||
|
return township.strip()
|
||||||
|
elif isinstance(township, list) and township:
|
||||||
|
return str(township[0]).strip()
|
||||||
|
return ""
|
||||||
|
else:
|
||||||
|
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)
|
||||||
|
|
||||||
|
# 1. 查询 administrative_mapping_45 中的区域数据,排除超大围栏 shape
|
||||||
|
query_district = {
|
||||||
|
"_source": {
|
||||||
|
"excludes": ["shape", "geo_shape", "boundary", "geometry", "polygon"]
|
||||||
|
},
|
||||||
|
"query": {
|
||||||
|
"bool": {
|
||||||
|
"must": [
|
||||||
|
{"term": {"type": "区域"}}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
print(f"[{datetime.now()}] 正在扫描区域数据 (type='区域')...")
|
||||||
|
district_docs = es_client.scan(index=INDEX_NAME, query=query_district)
|
||||||
|
|
||||||
|
diff_list = []
|
||||||
|
missing_loc_list = []
|
||||||
|
total_districts = 0
|
||||||
|
processed_count = 0
|
||||||
|
|
||||||
|
for hit in district_docs:
|
||||||
|
total_districts += 1
|
||||||
|
source = hit.get("_source", {})
|
||||||
|
doc_id = hit.get("_id")
|
||||||
|
|
||||||
|
province = str(source.get("province", "")).strip()
|
||||||
|
city = source.get("city", "")
|
||||||
|
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", {})
|
||||||
|
|
||||||
|
lon = location.get("lon") if isinstance(location, dict) else None
|
||||||
|
lat = location.get("lat") if isinstance(location, dict) else None
|
||||||
|
|
||||||
|
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)} 条, 缺少经纬度 {len(missing_loc_list)} 条...")
|
||||||
|
|
||||||
|
# 2. 调用高德 API 获取 township(传入可配置的 amap_key)
|
||||||
|
amap_township = get_amap_township(lon, lat, key=amap_key)
|
||||||
|
|
||||||
|
# 3. 根据民政部区划代码 mzb_district_code 查询该区域下 has_gov='是' 的街道
|
||||||
|
query_street = {
|
||||||
|
"_source": {
|
||||||
|
"excludes": ["shape", "geo_shape", "boundary", "geometry", "polygon"]
|
||||||
|
},
|
||||||
|
"query": {
|
||||||
|
"bool": {
|
||||||
|
"must": [
|
||||||
|
{"term": {"type": "乡镇街道"}},
|
||||||
|
{"term": {"mzb_district_code": str(mzb_district_code)}},
|
||||||
|
{"term": {"has_gov": "是"}}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"from": 0,
|
||||||
|
"size": 10
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
res_street = es_client.elastic_client.search(index=INDEX_NAME, body=query_street)
|
||||||
|
street_hits = res_street.get("hits", {}).get("hits", [])
|
||||||
|
except Exception as e:
|
||||||
|
print(f"查询街道数据异常 [{mzb_district_code}]: {e}")
|
||||||
|
street_hits = []
|
||||||
|
|
||||||
|
es_gov_streets = []
|
||||||
|
for s_hit in street_hits:
|
||||||
|
s_source = s_hit.get("_source", {})
|
||||||
|
# street 字段名称可能为 street、name 或 township
|
||||||
|
s_name = s_source.get("street") or s_source.get("name") or s_source.get("township") or ""
|
||||||
|
if s_name:
|
||||||
|
es_gov_streets.append(s_name)
|
||||||
|
|
||||||
|
es_gov_street_str = ",".join(es_gov_streets)
|
||||||
|
|
||||||
|
# 4. 对比 ES 中的街道名称和高德 township
|
||||||
|
# 不一致的情况:没有标记街道、或者标记的街道与高德不匹配
|
||||||
|
is_diff = False
|
||||||
|
if not es_gov_streets:
|
||||||
|
# ES中没有标记 has_gov='是' 的乡镇街道
|
||||||
|
is_diff = True
|
||||||
|
else:
|
||||||
|
# 判断高德 township 是否在标记列表中(考虑后缀差异如镇/街道,或完全不相等)
|
||||||
|
if amap_township not in es_gov_streets:
|
||||||
|
# 简单清洗匹配(如去掉“街道/镇/乡”后是否相同)
|
||||||
|
cleaned_amap = amap_township.replace("街道", "").replace("镇", "").replace("乡", "") if amap_township else ""
|
||||||
|
cleaned_es = [s.replace("街道", "").replace("镇", "").replace("乡", "") for s in es_gov_streets]
|
||||||
|
if not cleaned_amap or cleaned_amap not in cleaned_es:
|
||||||
|
is_diff = True
|
||||||
|
|
||||||
|
if is_diff:
|
||||||
|
diff_list.append({
|
||||||
|
"ES文档ID": doc_id,
|
||||||
|
"省份": province,
|
||||||
|
"城市": city,
|
||||||
|
"区域": district,
|
||||||
|
"民政部区划代码": mzb_district_code,
|
||||||
|
"统计局区划代码": tjj_district_code,
|
||||||
|
"经度(lon)": lon,
|
||||||
|
"纬度(lat)": lat,
|
||||||
|
"ES库中县政府所在街道(has_gov=是)": es_gov_street_str if es_gov_street_str else "【未标记】",
|
||||||
|
"高德逆地理街道(township)": amap_township if amap_township else "【高德未返回】",
|
||||||
|
"排查时间": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
})
|
||||||
|
|
||||||
|
print(f"[{datetime.now()}] 扫描完成!共遍历有效区域: {processed_count} 个,缺少经纬度区域: {len(missing_loc_list)} 个,发现不一致/缺失街道: {len(diff_list)} 条")
|
||||||
|
|
||||||
|
# 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")
|
||||||
|
|
||||||
|
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"
|
||||||
|
cc_receiver = "daijinshui@fangjia.com"
|
||||||
|
subject = f"【人工审核】县政府所在乡镇街道差异排查报告 - {datetime.now().strftime('%Y-%m-%d')}"
|
||||||
|
html_content = f"""
|
||||||
|
<h3>王老师:</h3>
|
||||||
|
<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)} 条(见 Sheet: 街道差异名单)</li>
|
||||||
|
<li><b>缺少经纬度待补全区域数:</b> {len(missing_loc_list)} 个(见 Sheet: 缺少经纬度区域)</li>
|
||||||
|
</ul>
|
||||||
|
<p>详细名单已整理在附件 Excel 中,请人工审核确认。</p>
|
||||||
|
"""
|
||||||
|
|
||||||
|
print(f"正在发送审核邮件至: {receiver}, 抄送: {cc_receiver} ...")
|
||||||
|
send_email(
|
||||||
|
to=receiver,
|
||||||
|
subject=subject,
|
||||||
|
html_content=html_content,
|
||||||
|
files=[excel_path],
|
||||||
|
cc=cc_receiver
|
||||||
|
)
|
||||||
|
print("邮件发送完成!")
|
||||||
|
|
||||||
|
|
||||||
|
# Airflow DAG 定义:每月1号上午9:00执行(北京时间)
|
||||||
|
with DAG(
|
||||||
|
dag_id="check_gov_township_diff_dag",
|
||||||
|
schedule="0 9 1 * *",
|
||||||
|
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:
|
||||||
|
|
||||||
|
check_task = PythonOperator(
|
||||||
|
task_id="check_gov_township_diff_task",
|
||||||
|
python_callable=check_gov_township_diff
|
||||||
|
)
|
||||||
Reference in New Issue
Block a user