Compare commits
41 Commits
aed37e0759
..
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 | |||
| 5603858a93 | |||
| bf2923bdc4 | |||
| fff45fbd37 | |||
| 726ac630f5 | |||
| 5110fee974 | |||
| 77186ee35c | |||
| ac01d98e08 | |||
| d04bdbd464 | |||
| 6dae2f895c | |||
| 3f09013747 | |||
| 4721f23827 | |||
| e36d16cbdd | |||
| b7534064aa | |||
| a11383312e | |||
| eddb99892a | |||
| aee4c00628 | |||
| bfcdb591d3 | |||
| 9467a62152 | |||
| 327b36e5a0 |
@@ -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/*
|
||||||
+23
-23
@@ -1,23 +1,23 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
# from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
# import pendulum
|
||||||
from airflow import DAG
|
# from airflow import DAG
|
||||||
|
#
|
||||||
with DAG(
|
# with DAG(
|
||||||
dag_id="ai_stock_dag",
|
# dag_id="ai_stock_dag",
|
||||||
# 每天运行
|
# # 每天运行
|
||||||
schedule="30 8 * * 1-5",
|
# schedule="30 8 * * 1-5",
|
||||||
start_date=pendulum.datetime(2025, 11, 10, tz="Asia/Shanghai"),
|
# start_date=pendulum.datetime(2025, 11, 10, tz="Asia/Shanghai"),
|
||||||
catchup=True,
|
# catchup=True,
|
||||||
tags=["ai_stock"],
|
# tags=["ai_stock"],
|
||||||
) as dag:
|
# ) as dag:
|
||||||
|
#
|
||||||
t1 = BashOperator(
|
# t1 = BashOperator(
|
||||||
task_id='stock_strategy',
|
# task_id='stock_strategy',
|
||||||
bash_command='python /opt/airflow/dags/repo/dags/ai/stock/stock_strategy.py',
|
# bash_command='python /opt/airflow/dags/repo/dags/ai/stock/stock_strategy.py',
|
||||||
)
|
# )
|
||||||
|
#
|
||||||
t2 = BashOperator(
|
# t2 = BashOperator(
|
||||||
task_id='ai_stock',
|
# task_id='ai_stock',
|
||||||
bash_command='python /opt/airflow/dags/repo/dags/ai/stock/stock.py',
|
# bash_command='python /opt/airflow/dags/repo/dags/ai/stock/stock.py',
|
||||||
)
|
# )
|
||||||
t1 >> t2
|
# t1 >> t2
|
||||||
+38
-38
@@ -1,38 +1,38 @@
|
|||||||
from goojia_utils import MysqlClient, ArkAIClient, dingutils
|
# from goojia_utils import MysqlClient, ArkAIClient, dingutils
|
||||||
from goojia_utils import dateutils
|
# from goojia_utils import dateutils
|
||||||
from datetime import datetime
|
# from datetime import datetime
|
||||||
import requests
|
# import requests
|
||||||
|
#
|
||||||
db_util = MysqlClient(
|
# db_util = MysqlClient(
|
||||||
host="192.168.0.93",
|
# host="192.168.0.93",
|
||||||
port=3306,
|
# port=3306,
|
||||||
database="stock",
|
# database="stock",
|
||||||
user="root",
|
# user="root",
|
||||||
password="Goojia123456"
|
# password="Goojia123456"
|
||||||
)
|
# )
|
||||||
date = int(dateutils.format_date(dateutils.add_months(datetime.today(), months=-1), fm='%Y%m%d'))
|
# date = int(dateutils.format_date(dateutils.add_months(datetime.today(), months=-1), fm='%Y%m%d'))
|
||||||
select_stocks = db_util.scan_by_sql_to_data_frame("select ts_code as 股票代码, stock_name as 股票名称,close as 股价, pe as PE,turnover_rate as 换手率 from mu_stocks_new where `trade_date`= (select max(`trade_date`) from mu_stocks_new)")
|
# select_stocks = db_util.scan_by_sql_to_data_frame("select ts_code as 股票代码, stock_name as 股票名称,close as 股价, pe as PE,turnover_rate as 换手率 from mu_stocks_new where `trade_date`= (select max(`trade_date`) from mu_stocks_new)")
|
||||||
stat = db_util.scan_by_sql_to_data_frame(f"select ts_code as 股票代码, count(ts_code) as 命中次数 from mu_stocks_new where `trade_date` > {date} group by ts_code")
|
# stat = db_util.scan_by_sql_to_data_frame(f"select ts_code as 股票代码, count(ts_code) as 命中次数 from mu_stocks_new where `trade_date` > {date} group by ts_code")
|
||||||
select_stocks = select_stocks.merge(stat, on='股票代码', how='left')
|
# select_stocks = select_stocks.merge(stat, on='股票代码', how='left')
|
||||||
select_stocks['命中次数'] = select_stocks['命中次数'].fillna(0)
|
# select_stocks['命中次数'] = select_stocks['命中次数'].fillna(0)
|
||||||
select_stocks = select_stocks.sort_values(by=['命中次数', 'PE'], ascending=[False, True])
|
# select_stocks = select_stocks.sort_values(by=['命中次数', 'PE'], ascending=[False, True])
|
||||||
def df_to_nested_list(df):
|
# def df_to_nested_list(df):
|
||||||
"""转换为嵌套的 Markdown 列表"""
|
# """转换为嵌套的 Markdown 列表"""
|
||||||
lines = []
|
# lines = []
|
||||||
i= 1
|
# i= 1
|
||||||
for _, row in df.iterrows():
|
# for _, row in df.iterrows():
|
||||||
lines.append(f"{i}. **{row['股票名称']}** ({row['股票代码']}) PE: {row['PE']} 股价: {row['股价']:.2f} 出现次数: {row['命中次数']} 换手率: {row['换手率']:.2f}")
|
# lines.append(f"{i}. **{row['股票名称']}** ({row['股票代码']}) PE: {row['PE']} 股价: {row['股价']:.2f} 出现次数: {row['命中次数']} 换手率: {row['换手率']:.2f}")
|
||||||
i = i + 1
|
# i = i + 1
|
||||||
return '\n'.join(lines)
|
# return '\n'.join(lines)
|
||||||
data = {
|
# data = {
|
||||||
"msgtype": "markdown",
|
# "msgtype": "markdown",
|
||||||
"markdown": {
|
# "markdown": {
|
||||||
"title": dateutils.format_date(datetime.today(), fm='%Y%m%d') + "选股策略播报",
|
# "title": dateutils.format_date(datetime.today(), fm='%Y%m%d') + "选股策略播报",
|
||||||
"text": df_to_nested_list(select_stocks)
|
# "text": df_to_nested_list(select_stocks)
|
||||||
}
|
# }
|
||||||
}
|
# }
|
||||||
access_token = "1e5f9aaeb90b091bc79652b52800cad2f1dee1ac0990149252511965f6d1c12a"
|
# access_token = "1e5f9aaeb90b091bc79652b52800cad2f1dee1ac0990149252511965f6d1c12a"
|
||||||
# 发送消息至群
|
# # 发送消息至群
|
||||||
msg = requests.post(url='https://oapi.dingtalk.com/robot/send?access_token=' + access_token, json=data).json()
|
# msg = requests.post(url='https://oapi.dingtalk.com/robot/send?access_token=' + access_token, json=data).json()
|
||||||
msg = requests.post(url='https://oapi.dingtalk.com/robot/send?access_token=45ac47a34dc5491535d77d643512244a85d91d7e74676e9c42446dc06357326e', json=data).json()
|
# msg = requests.post(url='https://oapi.dingtalk.com/robot/send?access_token=45ac47a34dc5491535d77d643512244a85d91d7e74676e9c42446dc06357326e', json=data).json()
|
||||||
print(msg)
|
# print(msg)
|
||||||
@@ -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
|
||||||
|
)
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from goojia_utils import ElasticSearchClient, commutils, dateutils, areautils, ClickHouseClient
|
from goojia_utils import ElasticSearchClient, commutils, dateutils, areautils, MAIN_MONGO_CLIENT
|
||||||
from elasticsearch import helpers
|
from elasticsearch import helpers
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
import sys
|
import sys
|
||||||
@@ -13,7 +13,7 @@ mutex = Lock()
|
|||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.206')
|
es206_client = ElasticSearchClient(host='192.168.0.206')
|
||||||
es89_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
es89_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
||||||
tmp_ck = ClickHouseClient(database='tmp')
|
community_summary_conn = MAIN_MONGO_CLIENT.get_collection('tmp', 'community_summary')
|
||||||
|
|
||||||
index_name = "community_summary"
|
index_name = "community_summary"
|
||||||
m_date = dateutils.iso_format()
|
m_date = dateutils.iso_format()
|
||||||
@@ -113,10 +113,10 @@ def find_around_price_item(seaweed):
|
|||||||
|
|
||||||
def sync(city=None):
|
def sync(city=None):
|
||||||
log.info("开始同步消费数据...")
|
log.info("开始同步消费数据...")
|
||||||
tmp_sql = f"select * from community_summary "
|
query = {}
|
||||||
if pd.notna(city):
|
if pd.notna(city):
|
||||||
tmp_sql += f" where city='{city}' "
|
query['city'] = city
|
||||||
seaweed_df = tmp_ck.read_sql_query(tmp_sql)
|
seaweed_df = pd.DataFrame(list(community_summary_conn.find(query)))
|
||||||
|
|
||||||
seaweed_list = list()
|
seaweed_list = list()
|
||||||
seaweed_df.apply(lambda x: seaweed_list.append(dict(x)), axis=1)
|
seaweed_df.apply(lambda x: seaweed_list.append(dict(x)), axis=1)
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from goojia_utils import ElasticSearchClient, commutils, dateutils, ClickHouseClient
|
from goojia_utils import ElasticSearchClient, commutils, dateutils, MAIN_MONGO_CLIENT
|
||||||
from elasticsearch import helpers
|
from elasticsearch import helpers
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from threading import Lock
|
from threading import Lock
|
||||||
@@ -11,7 +11,7 @@ import sys
|
|||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
||||||
tmp_ck = ClickHouseClient(database="tmp")
|
community_summary_conn = MAIN_MONGO_CLIENT.get_collection('tmp', 'community_summary')
|
||||||
|
|
||||||
index_name = "community_summary"
|
index_name = "community_summary"
|
||||||
path = "/home/airflow/data/community"
|
path = "/home/airflow/data/community"
|
||||||
@@ -90,10 +90,10 @@ def deal(actions, item):
|
|||||||
|
|
||||||
def sync(city=None):
|
def sync(city=None):
|
||||||
log.info(f"开始同步商圈至206 {index_name}")
|
log.info(f"开始同步商圈至206 {index_name}")
|
||||||
tmp_sql = f"select * from community_summary "
|
query = {}
|
||||||
if pd.notna(city):
|
if pd.notna(city):
|
||||||
tmp_sql += f" where city='{city}'"
|
query['city'] = city
|
||||||
seaweed_df = tmp_ck.read_sql_query(tmp_sql)
|
seaweed_df = pd.DataFrame(list(community_summary_conn.find(query)))
|
||||||
|
|
||||||
actions = list()
|
actions = list()
|
||||||
with ThreadPoolExecutor(max_workers=30) as pool:
|
with ThreadPoolExecutor(max_workers=30) as pool:
|
||||||
|
|||||||
@@ -1,9 +1,40 @@
|
|||||||
"""
|
"""
|
||||||
同步小区基本信息至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
|
||||||
from goojia_utils import MAIN_MONGO_CLIENT, ElasticSearchClient, commutils, dateutils, ClickHouseClient
|
import numpy as np
|
||||||
|
|
||||||
|
# 兼容性补丁:解决 goojia_utils.ClickHouseClient.to_sql_plus 在将 DataFrame 写入 ClickHouse 时,
|
||||||
|
# 对含有 list/array 类型的列(如 alias)进行 pd.notna(item) 判定时导致 ValueError 的 bug
|
||||||
|
_orig_notna = pd.notna
|
||||||
|
def patched_notna(obj):
|
||||||
|
if isinstance(obj, (list, tuple, np.ndarray, dict, set)):
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
res = _orig_notna(obj)
|
||||||
|
if hasattr(res, 'any'):
|
||||||
|
return bool(res.any())
|
||||||
|
elif isinstance(res, (list, np.ndarray)):
|
||||||
|
return any(res)
|
||||||
|
return res
|
||||||
|
except Exception:
|
||||||
|
return True
|
||||||
|
|
||||||
|
pd.notna = patched_notna
|
||||||
|
pd.isna = lambda x: not patched_notna(x)
|
||||||
|
import pandas
|
||||||
|
pandas.notna = patched_notna
|
||||||
|
pandas.isna = lambda x: not patched_notna(x)
|
||||||
|
|
||||||
|
from goojia_utils import MAIN_MONGO_CLIENT, ElasticSearchClient, commutils, dateutils
|
||||||
from elasticsearch import helpers
|
from elasticsearch import helpers
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
@@ -11,7 +42,7 @@ import sys
|
|||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
||||||
tmp_ck = ClickHouseClient(database='tmp')
|
community_summary_conn = MAIN_MONGO_CLIENT.get_collection('tmp', 'community_summary')
|
||||||
|
|
||||||
index_name = "community_summary"
|
index_name = "community_summary"
|
||||||
m_date = dateutils.iso_format()
|
m_date = dateutils.iso_format()
|
||||||
@@ -115,11 +146,11 @@ def deal_comm(community_summary_df, seaweed_df):
|
|||||||
def sync(city=None):
|
def sync(city=None):
|
||||||
log.info(f"开始同步小区基本属性至206 {index_name}...")
|
log.info(f"开始同步小区基本属性至206 {index_name}...")
|
||||||
seaweed_query = {'status': 0, 'cat': 'district'}
|
seaweed_query = {'status': 0, 'cat': 'district'}
|
||||||
ck_sql = "ALTER TABLE tmp.community_summary DELETE WHERE 1=1 "
|
mongo_delete_query = {}
|
||||||
if pd.notna(city):
|
if pd.notna(city):
|
||||||
seaweed_query['city'] = city
|
seaweed_query['city'] = city
|
||||||
ck_sql += " AND city='" + city + "'"
|
mongo_delete_query['city'] = city
|
||||||
tmp_ck.execute(ck_sql)
|
community_summary_conn.delete_many(mongo_delete_query)
|
||||||
|
|
||||||
seaweed_df = pd.DataFrame(
|
seaweed_df = pd.DataFrame(
|
||||||
list(seaweed_conn.find(seaweed_query, {'city': 1, 'region': 1, 'name': 1, 'lng': 1, 'lat': 1,
|
list(seaweed_conn.find(seaweed_query, {'city': 1, 'region': 1, 'name': 1, 'lng': 1, 'lat': 1,
|
||||||
@@ -156,9 +187,16 @@ def sync(city=None):
|
|||||||
|
|
||||||
# 写入csv文件,防止小区变动导致的后续过程更新报错,
|
# 写入csv文件,防止小区变动导致的后续过程更新报错,
|
||||||
# seaweed_df.to_csv(path + '/seaweed.csv', sep='@', encoding='UTF-8', index=False)
|
# seaweed_df.to_csv(path + '/seaweed.csv', sep='@', encoding='UTF-8', index=False)
|
||||||
# 写入中间表clickhouse,解决多worker节点问题
|
# 写入中间集合 MongoDB, 解决分布式 Worker 节点的共享问题
|
||||||
tmp_ck.to_sql_plus(seaweed_df[['_id', 'city', 'region', 'name', 'lng', 'lat', 'alias', 'estate_type2', 'build_type',
|
insert_cols = ['_id', 'city', 'region', 'name', 'lng', 'lat', 'alias', 'estate_type2', 'build_type',
|
||||||
'household_count', 'block', 'estate_charge', 'finish_building_date']], 'community_summary')
|
'household_count', 'block', 'estate_charge', 'finish_building_date']
|
||||||
|
records = seaweed_df[insert_cols].to_dict(orient='records')
|
||||||
|
if len(records) > 0:
|
||||||
|
log.info(f"正在写入 MongoDB community_summary 中间集合,共 {len(records)} 条记录...")
|
||||||
|
batch_size = 5000
|
||||||
|
for i in range(0, len(records), batch_size):
|
||||||
|
community_summary_conn.insert_many(records[i:i + batch_size])
|
||||||
|
log.info("MongoDB community_summary 写入完毕。")
|
||||||
|
|
||||||
actions = list()
|
actions = list()
|
||||||
# 对于存在的更新
|
# 对于存在的更新
|
||||||
|
|||||||
@@ -1,9 +1,25 @@
|
|||||||
"""
|
"""
|
||||||
同步删除小区基本信息至ES206
|
同步删除小区基本信息至ES206
|
||||||
"""
|
"""
|
||||||
|
# 兼容性补丁:解决 Elasticsearch 8.x/9.x 客户端在老版本 ES 集群上因 compatible-with 头部导致的 ApiError(406)
|
||||||
|
try:
|
||||||
|
import elasticsearch
|
||||||
|
ver = getattr(elasticsearch, '__version__', None)
|
||||||
|
if ver and not str(ver).startswith('7.'):
|
||||||
|
original_init = elasticsearch.Elasticsearch.__init__
|
||||||
|
def patched_init(self, *args, **kwargs):
|
||||||
|
headers = kwargs.get('headers', {})
|
||||||
|
headers['Accept'] = 'application/json'
|
||||||
|
headers['Content-Type'] = 'application/json'
|
||||||
|
kwargs['headers'] = headers
|
||||||
|
original_init(self, *args, **kwargs)
|
||||||
|
elasticsearch.Elasticsearch.__init__ = patched_init
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from goojia_utils import MAIN_MONGO_CLIENT, ElasticSearchClient, commutils, dateutils, ClickHouseClient
|
from goojia_utils import MAIN_MONGO_CLIENT, ElasticSearchClient, commutils, dateutils
|
||||||
from elasticsearch import helpers
|
from elasticsearch import helpers
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
@@ -11,7 +27,6 @@ import sys
|
|||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
||||||
tmp_ck = ClickHouseClient(database='tmp')
|
|
||||||
|
|
||||||
index_name = "community_summary"
|
index_name = "community_summary"
|
||||||
m_date = dateutils.iso_format()
|
m_date = dateutils.iso_format()
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from goojia_utils import ElasticSearchClient, commutils, dateutils, poiutils, ClickHouseClient
|
from goojia_utils import ElasticSearchClient, commutils, dateutils, poiutils, MAIN_MONGO_CLIENT
|
||||||
from elasticsearch import helpers
|
from elasticsearch import helpers
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from threading import Lock
|
from threading import Lock
|
||||||
@@ -11,7 +11,7 @@ import sys
|
|||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
||||||
tmp_ck = ClickHouseClient(database="tmp")
|
community_summary_conn = MAIN_MONGO_CLIENT.get_collection('tmp', 'community_summary')
|
||||||
|
|
||||||
index_name = "community_summary"
|
index_name = "community_summary"
|
||||||
path = "/home/airflow/data/community"
|
path = "/home/airflow/data/community"
|
||||||
@@ -66,10 +66,10 @@ def deal(actions, item):
|
|||||||
|
|
||||||
def sync(city=None):
|
def sync(city=None):
|
||||||
log.info(f"开始同步教育资源【幼儿园、大学】至206 {index_name}")
|
log.info(f"开始同步教育资源【幼儿园、大学】至206 {index_name}")
|
||||||
tmp_sql = f"select * from community_summary "
|
query = {}
|
||||||
if pd.notna(city):
|
if pd.notna(city):
|
||||||
tmp_sql += f" where city='{city}'"
|
query['city'] = city
|
||||||
seaweed_df = tmp_ck.read_sql_query(tmp_sql)
|
seaweed_df = pd.DataFrame(list(community_summary_conn.find(query)))
|
||||||
|
|
||||||
actions = list()
|
actions = list()
|
||||||
with ThreadPoolExecutor(max_workers=30) as pool:
|
with ThreadPoolExecutor(max_workers=30) as pool:
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from goojia_utils import ElasticSearchClient, commutils, dateutils, poiutils, ClickHouseClient
|
from goojia_utils import ElasticSearchClient, commutils, dateutils, poiutils, MAIN_MONGO_CLIENT
|
||||||
from elasticsearch import helpers
|
from elasticsearch import helpers
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from threading import Lock
|
from threading import Lock
|
||||||
@@ -11,7 +11,7 @@ import sys
|
|||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
||||||
tmp_ck = ClickHouseClient(database="tmp")
|
community_summary_conn = MAIN_MONGO_CLIENT.get_collection('tmp', 'community_summary')
|
||||||
|
|
||||||
index_name = "community_summary"
|
index_name = "community_summary"
|
||||||
path = "/home/airflow/data/community"
|
path = "/home/airflow/data/community"
|
||||||
@@ -81,10 +81,10 @@ def deal(actions, item):
|
|||||||
def sync(city=None):
|
def sync(city=None):
|
||||||
log.info(f"开始同步教育资源【小学、中学】至206 {index_name}")
|
log.info(f"开始同步教育资源【小学、中学】至206 {index_name}")
|
||||||
|
|
||||||
tmp_sql = f"select * from community_summary "
|
query = {}
|
||||||
if pd.notna(city):
|
if pd.notna(city):
|
||||||
tmp_sql += f" where city='{city}'"
|
query['city'] = city
|
||||||
seaweed_df = tmp_ck.read_sql_query(tmp_sql)
|
seaweed_df = pd.DataFrame(list(community_summary_conn.find(query)))
|
||||||
|
|
||||||
actions = list()
|
actions = list()
|
||||||
with ThreadPoolExecutor(max_workers=30) as pool:
|
with ThreadPoolExecutor(max_workers=30) as pool:
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from goojia_utils import ElasticSearchClient, commutils, dateutils, poiutils, ClickHouseClient
|
from goojia_utils import ElasticSearchClient, commutils, dateutils, poiutils, MAIN_MONGO_CLIENT
|
||||||
from elasticsearch import helpers
|
from elasticsearch import helpers
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from threading import Lock
|
from threading import Lock
|
||||||
@@ -11,7 +11,7 @@ import sys
|
|||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
||||||
tmp_ck = ClickHouseClient(database='tmp')
|
community_summary_conn = MAIN_MONGO_CLIENT.get_collection('tmp', 'community_summary')
|
||||||
|
|
||||||
index_name = "community_summary"
|
index_name = "community_summary"
|
||||||
path = "/home/airflow/data/community"
|
path = "/home/airflow/data/community"
|
||||||
@@ -78,10 +78,10 @@ def deal(actions, item):
|
|||||||
|
|
||||||
def sync(city=None):
|
def sync(city=None):
|
||||||
log.info(f"开始同步生活配套至206 {index_name}")
|
log.info(f"开始同步生活配套至206 {index_name}")
|
||||||
tmp_sql = f"select * from community_summary "
|
query = {}
|
||||||
if pd.notna(city):
|
if pd.notna(city):
|
||||||
tmp_sql += f" where city='{city}'"
|
query['city'] = city
|
||||||
seaweed_df = tmp_ck.read_sql_query(tmp_sql)
|
seaweed_df = pd.DataFrame(list(community_summary_conn.find(query)))
|
||||||
|
|
||||||
actions = list()
|
actions = list()
|
||||||
with ThreadPoolExecutor(max_workers=30) as pool:
|
with ThreadPoolExecutor(max_workers=30) as pool:
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from goojia_utils import MAIN_MONGO_CLIENT, ElasticSearchClient, commutils, dateutils, ClickHouseClient, poiutils
|
from goojia_utils import MAIN_MONGO_CLIENT, ElasticSearchClient, commutils, dateutils, poiutils
|
||||||
from elasticsearch import helpers
|
from elasticsearch import helpers
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from threading import Lock
|
from threading import Lock
|
||||||
@@ -12,7 +12,7 @@ import sys
|
|||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
||||||
tmp_ck = ClickHouseClient(database='tmp')
|
community_summary_conn = MAIN_MONGO_CLIENT.get_collection('tmp', 'community_summary')
|
||||||
|
|
||||||
index_name = "community_summary"
|
index_name = "community_summary"
|
||||||
path = "/home/airflow/data/community"
|
path = "/home/airflow/data/community"
|
||||||
@@ -66,10 +66,10 @@ def deal(actions, item):
|
|||||||
|
|
||||||
def sync(city=None):
|
def sync(city=None):
|
||||||
log.info(f"开始同步医院至206 {index_name}")
|
log.info(f"开始同步医院至206 {index_name}")
|
||||||
tmp_sql = f"select * from community_summary "
|
query = {}
|
||||||
if pd.notna(city):
|
if pd.notna(city):
|
||||||
tmp_sql += f" where city='{city}'"
|
query['city'] = city
|
||||||
seaweed_df = tmp_ck.read_sql_query(tmp_sql)
|
seaweed_df = pd.DataFrame(list(community_summary_conn.find(query)))
|
||||||
|
|
||||||
actions = list()
|
actions = list()
|
||||||
with ThreadPoolExecutor(max_workers=30) as pool:
|
with ThreadPoolExecutor(max_workers=30) as pool:
|
||||||
|
|||||||
@@ -3,13 +3,13 @@
|
|||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from goojia_utils import ElasticSearchClient, commutils, dateutils, areautils, ClickHouseClient
|
from goojia_utils import ElasticSearchClient, commutils, dateutils, areautils, MAIN_MONGO_CLIENT
|
||||||
from elasticsearch import helpers
|
from elasticsearch import helpers
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
||||||
tmp_ck = ClickHouseClient(database='tmp')
|
community_summary_conn = MAIN_MONGO_CLIENT.get_collection('tmp', 'community_summary')
|
||||||
|
|
||||||
index_name = "community_summary"
|
index_name = "community_summary"
|
||||||
path = "/home/airflow/data/community"
|
path = "/home/airflow/data/community"
|
||||||
@@ -42,7 +42,7 @@ def build_doc(item):
|
|||||||
|
|
||||||
|
|
||||||
def sync_by_city(city):
|
def sync_by_city(city):
|
||||||
seaweed_df = tmp_ck.read_sql_query(f"select _id, city, region, name from community_summary where city='{city}'")
|
seaweed_df = pd.DataFrame(list(community_summary_conn.find({"city": city}, {"_id": 1, "city": 1, "region": 1, "name": 1})))
|
||||||
if len(seaweed_df) == 0:
|
if len(seaweed_df) == 0:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from goojia_utils import ElasticSearchClient, commutils, dateutils, ClickHouseClient
|
from goojia_utils import ElasticSearchClient, commutils, dateutils, MAIN_MONGO_CLIENT
|
||||||
from elasticsearch import helpers
|
from elasticsearch import helpers
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
import sys
|
import sys
|
||||||
@@ -12,7 +12,7 @@ from threading import Lock
|
|||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
||||||
tmp_ck = ClickHouseClient(database='tmp')
|
community_summary_conn = MAIN_MONGO_CLIENT.get_collection('tmp', 'community_summary')
|
||||||
|
|
||||||
index_name = "community_summary"
|
index_name = "community_summary"
|
||||||
path = "/home/airflow/data/community"
|
path = "/home/airflow/data/community"
|
||||||
@@ -134,10 +134,10 @@ def find_around_price_item(seaweed):
|
|||||||
def sync(city=None):
|
def sync(city=None):
|
||||||
log.info("开始同步相对价格排名数据...")
|
log.info("开始同步相对价格排名数据...")
|
||||||
|
|
||||||
tmp_sql = f"select * from community_summary "
|
query = {}
|
||||||
if pd.notna(city):
|
if pd.notna(city):
|
||||||
tmp_sql += f" where city='{city}'"
|
query['city'] = city
|
||||||
seaweed_df = tmp_ck.read_sql_query(tmp_sql)
|
seaweed_df = pd.DataFrame(list(community_summary_conn.find(query)))
|
||||||
|
|
||||||
seaweed_list = list()
|
seaweed_list = list()
|
||||||
seaweed_df.apply(lambda x: seaweed_list.append(dict(x)), axis=1)
|
seaweed_df.apply(lambda x: seaweed_list.append(dict(x)), axis=1)
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from goojia_utils import MAIN_MONGO_CLIENT, ElasticSearchClient, commutils, dateutils, ClickHouseClient
|
from goojia_utils import MAIN_MONGO_CLIENT, ElasticSearchClient, commutils, dateutils
|
||||||
from elasticsearch import helpers
|
from elasticsearch import helpers
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
import sys
|
import sys
|
||||||
@@ -12,7 +12,7 @@ from threading import Lock
|
|||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
||||||
tmp_ck = ClickHouseClient(database='tmp')
|
community_summary_conn = MAIN_MONGO_CLIENT.get_collection('tmp', 'community_summary')
|
||||||
|
|
||||||
index_name = "community_summary"
|
index_name = "community_summary"
|
||||||
path = "/home/airflow/data/community"
|
path = "/home/airflow/data/community"
|
||||||
@@ -33,10 +33,10 @@ def build_doc(item):
|
|||||||
def sync(city=None):
|
def sync(city=None):
|
||||||
log.info(f"开始同步出售信息至206 {index_name}")
|
log.info(f"开始同步出售信息至206 {index_name}")
|
||||||
|
|
||||||
tmp_sql = f"select * from community_summary "
|
query = {}
|
||||||
if pd.notna(city):
|
if pd.notna(city):
|
||||||
tmp_sql += f" where city='{city}'"
|
query['city'] = city
|
||||||
seaweed_df = tmp_ck.read_sql_query(tmp_sql)
|
seaweed_df = pd.DataFrame(list(community_summary_conn.find(query)))
|
||||||
|
|
||||||
with ThreadPoolExecutor(30) as pool:
|
with ThreadPoolExecutor(30) as pool:
|
||||||
def deal(index, item):
|
def deal(index, item):
|
||||||
|
|||||||
@@ -0,0 +1,231 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import logging
|
||||||
|
import pandas as pd
|
||||||
|
from datetime import datetime
|
||||||
|
from pymongo import UpdateOne
|
||||||
|
|
||||||
|
# 兼容性补丁:解决 Elasticsearch 8.x/9.x 客户端在老版本 ES 集群上因 compatible-with 头部导致的 ApiError(406)
|
||||||
|
os.environ["ELASTIC_CLIENT_APIVERSIONING"] = "0"
|
||||||
|
try:
|
||||||
|
import elasticsearch
|
||||||
|
ver = getattr(elasticsearch, '__version__', None)
|
||||||
|
if ver and not str(ver).startswith('7.'):
|
||||||
|
original_init = elasticsearch.Elasticsearch.__init__
|
||||||
|
def patched_init(self, *args, **kwargs):
|
||||||
|
headers = kwargs.get('headers', {})
|
||||||
|
headers['Accept'] = 'application/json'
|
||||||
|
headers['Content-Type'] = 'application/json'
|
||||||
|
kwargs['headers'] = headers
|
||||||
|
original_init(self, *args, **kwargs)
|
||||||
|
elasticsearch.Elasticsearch.__init__ = patched_init
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
from goojia_utils import MAIN_MONGO_CLIENT, ElasticSearchClient
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# 初始化 ES 206 客户端与 85 上的 MongoDB 集合
|
||||||
|
es206_client = ElasticSearchClient(host='192.168.0.206')
|
||||||
|
average_statistics_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'average_statistics')
|
||||||
|
|
||||||
|
index_name = "community"
|
||||||
|
|
||||||
|
# 映射关系:将 ES 中的 root 主域映射为 Mongo 表中的对应二手房价格 (_esf_price) 字段
|
||||||
|
ROOT_FIELD_MAP = {
|
||||||
|
"anjuke.com": "anjuke_esf_price", # 安居客
|
||||||
|
"lianjia.com": "lianjia_esf_price", # 链家
|
||||||
|
"ke.com": "beike_esf_price", # 贝壳
|
||||||
|
"beike.com": "beike_esf_price", # 贝壳
|
||||||
|
"fang.com": "soufang_esf_price", # 房天下/搜房
|
||||||
|
"soufang.com": "soufang_esf_price", # 搜房
|
||||||
|
"5i5j.com": "5i5j_esf_price", # 我爱我家
|
||||||
|
"centanet.com": "zhongyuan_esf_price", # 中原地产
|
||||||
|
"qfang.com": "qfang_esf_price", # Q房网
|
||||||
|
"leyoujia.com": "leyoujia_esf_price", # 乐有家
|
||||||
|
"zhuge.com": "zhugezhaofang_esf_price", # 诸葛找房
|
||||||
|
"zhugezhaofang.com": "zhugezhaofang_esf_price",
|
||||||
|
"jiwu.com": "jiwu_esf_price", # 吉屋
|
||||||
|
"house365.com": "365house_esf_price", # 365淘房
|
||||||
|
"365.com": "365house_esf_price",
|
||||||
|
"fanggugu.com": "fanggugu_esf_price", # 房估估
|
||||||
|
"yungujia.com": "yungujia_esf_price", # 云估价
|
||||||
|
"tuboshi.com": "tuboshi_esf_price", # 兔博士
|
||||||
|
"xiaozijia.com": "xiaozijia_esf_price", # 小资家
|
||||||
|
"fangdoudou.com": "fangdoudou_esf_price",# 房兜兜
|
||||||
|
"fangtan.com": "fangtan_esf_price", # 房探
|
||||||
|
"guoxinda.com": "gxd_esf_price", # 国信达
|
||||||
|
"gxd.com": "gxd_esf_price",
|
||||||
|
"xingfuli.com": "xingfuli_esf_price", # 幸福里
|
||||||
|
"maitian.cn": "maitian_esf_price", # 麦田房产
|
||||||
|
"maitian.com": "maitian_esf_price",
|
||||||
|
"sina.com.cn": "sina_esf_price", # 新浪二手房
|
||||||
|
"sina.com": "sina_esf_price",
|
||||||
|
"cric.com": "cric_esf_price", # 克而瑞
|
||||||
|
"ganji.com": "ganji_esf_price", # 赶集网
|
||||||
|
}
|
||||||
|
|
||||||
|
def parse_s_date(m_date_str):
|
||||||
|
"""
|
||||||
|
将 ES 抓取时间 '2022-06-17T13:12:47.148Z' 转化为整型 s_date YYYYMM (例如 202206)
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if pd.isna(m_date_str) or not isinstance(m_date_str, str):
|
||||||
|
return None
|
||||||
|
return int(m_date_str[:7].replace('-', ''))
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def sync_data(target_month=None):
|
||||||
|
"""
|
||||||
|
数据流式拉取、转换与批量 Upsert
|
||||||
|
"""
|
||||||
|
log.info("开始从 ES 206 的 community 索引拉取小区价格数据...")
|
||||||
|
|
||||||
|
# 构造 SQL,默认仅同步近 3 个月(90 天)内更新的数据,降低传输和存储开销
|
||||||
|
if target_month is not None:
|
||||||
|
try:
|
||||||
|
month_str = str(target_month)
|
||||||
|
year = int(month_str[:4])
|
||||||
|
month = int(month_str[4:6])
|
||||||
|
start_date = f"{year:04d}-{month:02d}-01T00:00:00"
|
||||||
|
if month == 12:
|
||||||
|
end_date = f"{year + 1:04d}-01-01T00:00:00"
|
||||||
|
else:
|
||||||
|
end_date = f"{year:04d}-{month + 1:02d}-01T00:00:00"
|
||||||
|
|
||||||
|
date_filter = f"and m_date >= '{start_date}' and m_date < '{end_date}'"
|
||||||
|
log.info(f"指定历史月份跑数,过滤条件: {start_date} 至 {end_date}")
|
||||||
|
except Exception as e:
|
||||||
|
log.error(f"解析指定月份失败,退回到默认的近3个月同步。Error: {e}")
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
three_months_ago = (datetime.now() - timedelta(days=90)).strftime('%Y-%m-%dT%H:%M:%S')
|
||||||
|
date_filter = f"and m_date >= '{three_months_ago}'"
|
||||||
|
else:
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
three_months_ago = (datetime.now() - timedelta(days=90)).strftime('%Y-%m-%dT%H:%M:%S')
|
||||||
|
date_filter = f"and 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 and avg_price > 0 {date_filter}"
|
||||||
|
|
||||||
|
# 城市手动过滤(可选,通过外部参数调度)
|
||||||
|
sys_city = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].isdigit() else None
|
||||||
|
if pd.notna(sys_city):
|
||||||
|
sql += f" and city = '{sys_city}'"
|
||||||
|
log.info(f"正在过滤目标城市: {sys_city}")
|
||||||
|
|
||||||
|
df = es206_client.scan_by_sql_to_data_frame(sql)
|
||||||
|
if df is None or len(df) == 0:
|
||||||
|
log.info("未从 ES 中获取到可用数据。")
|
||||||
|
return
|
||||||
|
|
||||||
|
log.info(f"成功读取到 {len(df)} 条原始记录。开始解析字段,并根据唯一键 (city, region, name, s_date) 进行内存合并...")
|
||||||
|
|
||||||
|
# 聚合内存合并,以支持多个不同 root (渠道来源) 的价格在同一个 (城市-行政区-小区名-月份) 唯一键文档中合并设置
|
||||||
|
grouped = {}
|
||||||
|
|
||||||
|
for idx, row in df.iterrows():
|
||||||
|
city = row.get('city')
|
||||||
|
region = row.get('region')
|
||||||
|
name = row.get('name')
|
||||||
|
avg_price = row.get('avg_price')
|
||||||
|
root = row.get('root')
|
||||||
|
m_date = row.get('m_date')
|
||||||
|
|
||||||
|
if pd.isna(city) or pd.isna(region) or pd.isna(name) or pd.isna(avg_price) or pd.isna(root):
|
||||||
|
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)
|
||||||
|
if s_date is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 若指定了目标月份过滤(如仅同步指定月份的数据)
|
||||||
|
if target_month is not None and s_date != int(target_month):
|
||||||
|
continue
|
||||||
|
|
||||||
|
field_name = ROOT_FIELD_MAP.get(root)
|
||||||
|
if not field_name:
|
||||||
|
continue
|
||||||
|
|
||||||
|
key = (city, region, name, s_date)
|
||||||
|
if key not in grouped:
|
||||||
|
grouped[key] = {}
|
||||||
|
|
||||||
|
# 多个相同 root 冲突时,此处保留最新或较高价格(以整型存储)
|
||||||
|
current_val = grouped[key].get(field_name)
|
||||||
|
if current_val is None or price_val > current_val:
|
||||||
|
grouped[key][field_name] = price_val
|
||||||
|
|
||||||
|
log.info(f"内存聚合清洗完毕。共获得 {len(grouped)} 组唯一索引项。开始构建批量 MongoDB UpdateOne upsert 任务...")
|
||||||
|
|
||||||
|
# 构建 Bulk Write Upsert 任务
|
||||||
|
actions = []
|
||||||
|
now = datetime.now()
|
||||||
|
|
||||||
|
for (city, region, name, s_date), fields_dict in grouped.items():
|
||||||
|
# 需要 $set 写入的所有第三方价格字段及最近修改时间
|
||||||
|
update_doc = {**fields_dict}
|
||||||
|
update_doc["m_date"] = now # ModificationDate 对应实体属性
|
||||||
|
|
||||||
|
query = {
|
||||||
|
"city": city,
|
||||||
|
"region": region,
|
||||||
|
"name": name,
|
||||||
|
"s_date": s_date
|
||||||
|
}
|
||||||
|
|
||||||
|
# Upsert 动作
|
||||||
|
action = UpdateOne(
|
||||||
|
query,
|
||||||
|
{
|
||||||
|
"$set": update_doc,
|
||||||
|
"$setOnInsert": {
|
||||||
|
"category": "district", # 默认对应小区类别 district
|
||||||
|
"date": now # 对应首建/大日期 longDate
|
||||||
|
}
|
||||||
|
},
|
||||||
|
upsert=True
|
||||||
|
)
|
||||||
|
actions.append(action)
|
||||||
|
|
||||||
|
total_actions = len(actions)
|
||||||
|
if total_actions == 0:
|
||||||
|
log.info("过滤处理后无数据需写入 MongoDB。")
|
||||||
|
return
|
||||||
|
|
||||||
|
log.info(f"开始向 192.168.0.85 数据库的 average_statistics 集合中分批写入 {total_actions} 条大批处理记录...")
|
||||||
|
|
||||||
|
# 5000条一笔批量执行写入,防止网络长连接超时或内存剧增
|
||||||
|
batch_size = 5000
|
||||||
|
for i in range(0, total_actions, batch_size):
|
||||||
|
batch_actions = actions[i:i + batch_size]
|
||||||
|
result = average_statistics_conn.bulk_write(batch_actions)
|
||||||
|
log.info(f"批次 {i // batch_size + 1} 写入情况: "
|
||||||
|
f"Matched={result.matched_count}, "
|
||||||
|
f"Upserted={result.upserted_count}, "
|
||||||
|
f"Modified={result.modified_count}")
|
||||||
|
|
||||||
|
log.info("数据同步流任务全部成功结束!")
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
# 支持传入参数如 `python sync_es_price_to_mongo.py 202401` 进行指定月份跑数
|
||||||
|
month_arg = None
|
||||||
|
if len(sys.argv) > 1:
|
||||||
|
arg = sys.argv[1]
|
||||||
|
if arg.isdigit() and len(arg) == 6:
|
||||||
|
month_arg = int(arg)
|
||||||
|
log.info(f"读取到指定月份运行参数: {month_arg}")
|
||||||
|
|
||||||
|
sync_data(target_month=month_arg)
|
||||||
@@ -4,12 +4,12 @@
|
|||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import sys
|
import sys
|
||||||
from goojia_utils import ElasticSearchClient, commutils, dateutils, ClickHouseClient
|
from goojia_utils import ElasticSearchClient, commutils, dateutils, MAIN_MONGO_CLIENT
|
||||||
from elasticsearch import helpers
|
from elasticsearch import helpers
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
||||||
tmp_ck = ClickHouseClient(database='tmp')
|
community_summary_conn = MAIN_MONGO_CLIENT.get_collection('tmp', 'community_summary')
|
||||||
|
|
||||||
index_name = "community_summary"
|
index_name = "community_summary"
|
||||||
path = "/home/airflow/data/community"
|
path = "/home/airflow/data/community"
|
||||||
@@ -28,11 +28,10 @@ def sync(city=None):
|
|||||||
|
|
||||||
cities = None
|
cities = None
|
||||||
|
|
||||||
tmp_sql = f"select * from community_summary "
|
query = {}
|
||||||
if pd.notna(city):
|
if pd.notna(city):
|
||||||
cities = [city]
|
query['city'] = city
|
||||||
tmp_sql += f" where city='{city}'"
|
seaweed_df = pd.DataFrame(list(community_summary_conn.find(query)))
|
||||||
seaweed_df = tmp_ck.read_sql_query(tmp_sql)
|
|
||||||
|
|
||||||
deal_price_df = commutils.get_deal_avg_price(cities, 3)
|
deal_price_df = commutils.get_deal_avg_price(cities, 3)
|
||||||
if len(deal_price_df) <= 0:
|
if len(deal_price_df) <= 0:
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from goojia_utils import ElasticSearchClient, commutils, dateutils, poiutils, ClickHouseClient
|
from goojia_utils import ElasticSearchClient, commutils, dateutils, poiutils, MAIN_MONGO_CLIENT
|
||||||
from elasticsearch import helpers
|
from elasticsearch import helpers
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from threading import Lock
|
from threading import Lock
|
||||||
@@ -11,7 +11,7 @@ import sys
|
|||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
||||||
tmp_ck = ClickHouseClient(database='tmp')
|
community_summary_conn = MAIN_MONGO_CLIENT.get_collection('tmp', 'community_summary')
|
||||||
|
|
||||||
index_name = "community_summary"
|
index_name = "community_summary"
|
||||||
path = "/home/airflow/data/community"
|
path = "/home/airflow/data/community"
|
||||||
@@ -72,10 +72,10 @@ def deal(actions, item):
|
|||||||
|
|
||||||
def sync(city=None):
|
def sync(city=None):
|
||||||
log.info(f"开始同步交通至206 {index_name}")
|
log.info(f"开始同步交通至206 {index_name}")
|
||||||
tmp_sql = f"select * from community_summary "
|
query = {}
|
||||||
if pd.notna(city):
|
if pd.notna(city):
|
||||||
tmp_sql += f" where city='{city}'"
|
query['city'] = city
|
||||||
seaweed_df = tmp_ck.read_sql_query(tmp_sql)
|
seaweed_df = pd.DataFrame(list(community_summary_conn.find(query)))
|
||||||
|
|
||||||
actions = list()
|
actions = list()
|
||||||
with ThreadPoolExecutor(max_workers=30) as pool:
|
with ThreadPoolExecutor(max_workers=30) as pool:
|
||||||
|
|||||||
@@ -1,82 +1,82 @@
|
|||||||
import logging
|
# import logging
|
||||||
import sys
|
# import sys
|
||||||
from goojia_utils import MAIN_MONGO_CLIENT, DIDATA_MONGO_CLIENT, areautils
|
# from goojia_utils import MAIN_MONGO_CLIENT, DIDATA_MONGO_CLIENT, areautils
|
||||||
from pymongo import UpdateOne
|
# from pymongo import UpdateOne
|
||||||
from bson.objectid import ObjectId
|
# from bson.objectid import ObjectId
|
||||||
import pandas as pd
|
# import pandas as pd
|
||||||
import time
|
# import time
|
||||||
|
#
|
||||||
log = logging.getLogger(__name__)
|
# log = logging.getLogger(__name__)
|
||||||
|
#
|
||||||
type = sys.argv[1] if len(sys.argv) > 1 else 'all'
|
# type = sys.argv[1] if len(sys.argv) > 1 else 'all'
|
||||||
log.info("同步类型:" + type)
|
# log.info("同步类型:" + type)
|
||||||
|
#
|
||||||
|
#
|
||||||
def sync_district_office(type):
|
# def sync_district_office(type):
|
||||||
if type != 'district' and type != 'office':
|
# if type != 'district' and type != 'office':
|
||||||
return
|
# return
|
||||||
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
# seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
||||||
seaweed_didata_conn = DIDATA_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
# seaweed_didata_conn = DIDATA_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
||||||
|
#
|
||||||
cities = areautils.get_all_cities()
|
# cities = areautils.get_all_cities()
|
||||||
update_date = int(round(time.time() * 1000))
|
# update_date = int(round(time.time() * 1000))
|
||||||
for city in cities:
|
# for city in cities:
|
||||||
actions = list()
|
# actions = list()
|
||||||
id_list = list()
|
# id_list = list()
|
||||||
for doc in seaweed_conn.find({'city': city, 'cat': type, 'status': 0},
|
# for doc in seaweed_conn.find({'city': city, 'cat': type, 'status': 0},
|
||||||
{'city': 1, 'region': 1, 'block': 1, 'cat': 1, 'name': 1, 'address': 1,
|
# {'city': 1, 'region': 1, 'block': 1, 'cat': 1, 'name': 1, 'address': 1,
|
||||||
'estate_type2': 1, 'township': 1, 'alias': 1, 'addr_alias': 1, 'lng': 1, 'lat': 1,
|
# 'estate_type2': 1, 'township': 1, 'alias': 1, 'addr_alias': 1, 'lng': 1, 'lat': 1,
|
||||||
'status': 1}) \
|
# 'status': 1}) \
|
||||||
.batch_size(10000):
|
# .batch_size(10000):
|
||||||
updateDict = {'city': doc['city'], 'region': doc['region'], 'category': doc['cat'], 'name': doc['name'],
|
# updateDict = {'city': doc['city'], 'region': doc['region'], 'category': doc['cat'], 'name': doc['name'],
|
||||||
'status': doc['status']}
|
# 'status': doc['status']}
|
||||||
if 'estate_type2' in doc:
|
# if 'estate_type2' in doc:
|
||||||
updateDict['estate_type'] = doc['estate_type2']
|
# updateDict['estate_type'] = doc['estate_type2']
|
||||||
|
#
|
||||||
id_list.append({'_id': doc['_id']})
|
# id_list.append({'_id': doc['_id']})
|
||||||
if 'block' in doc:
|
# if 'block' in doc:
|
||||||
updateDict['block'] = doc['block']
|
# updateDict['block'] = doc['block']
|
||||||
if 'address' in doc:
|
# if 'address' in doc:
|
||||||
updateDict['address'] = doc['address']
|
# updateDict['address'] = doc['address']
|
||||||
if 'township' in doc:
|
# if 'township' in doc:
|
||||||
updateDict['township'] = doc['township']
|
# updateDict['township'] = doc['township']
|
||||||
if 'alias' in doc:
|
# if 'alias' in doc:
|
||||||
updateDict['alias'] = doc['alias']
|
# updateDict['alias'] = doc['alias']
|
||||||
if 'addr_alias' in doc:
|
# if 'addr_alias' in doc:
|
||||||
updateDict['addr_alias'] = doc['addr_alias']
|
# updateDict['addr_alias'] = doc['addr_alias']
|
||||||
if 'lng' in doc and doc['lng'] is not None and str(doc['lng']) != 'nan':
|
# if 'lng' in doc and doc['lng'] is not None and str(doc['lng']) != 'nan':
|
||||||
updateDict['location'] = {'lon': doc['lng'] / 10 ** 10, 'lat': doc['lat'] / 10 ** 10}
|
# updateDict['location'] = {'lon': doc['lng'] / 10 ** 10, 'lat': doc['lat'] / 10 ** 10}
|
||||||
updateDict['update_date'] = update_date
|
# updateDict['update_date'] = update_date
|
||||||
action = UpdateOne({'_id': doc['_id']}, {'$set': updateDict}, upsert=True)
|
# action = UpdateOne({'_id': doc['_id']}, {'$set': updateDict}, upsert=True)
|
||||||
|
#
|
||||||
actions.append(action)
|
# actions.append(action)
|
||||||
if len(actions) == 10000:
|
# if len(actions) == 10000:
|
||||||
seaweed_didata_conn.bulk_write(actions)
|
# seaweed_didata_conn.bulk_write(actions)
|
||||||
actions.clear()
|
# actions.clear()
|
||||||
|
#
|
||||||
didata_id_df = pd.DataFrame(
|
# didata_id_df = pd.DataFrame(
|
||||||
list(seaweed_didata_conn.find({'city': city, 'category': type}, {'_id': 1}).batch_size(10000)))
|
# list(seaweed_didata_conn.find({'city': city, 'category': type}, {'_id': 1}).batch_size(10000)))
|
||||||
if len(didata_id_df) > 0:
|
# if len(didata_id_df) > 0:
|
||||||
didata_id_df = didata_id_df[['_id']]
|
# didata_id_df = didata_id_df[['_id']]
|
||||||
id_df = pd.DataFrame(id_list)
|
# id_df = pd.DataFrame(id_list)
|
||||||
deleted_seaweed_df = pd.concat([didata_id_df, id_df, id_df]).drop_duplicates(keep=False)
|
# deleted_seaweed_df = pd.concat([didata_id_df, id_df, id_df]).drop_duplicates(keep=False)
|
||||||
|
#
|
||||||
for deleted_seaweed_index, deleted_seaweed_item in deleted_seaweed_df.iterrows():
|
# for deleted_seaweed_index, deleted_seaweed_item in deleted_seaweed_df.iterrows():
|
||||||
action = UpdateOne({'_id': ObjectId(deleted_seaweed_item['_id'])},
|
# action = UpdateOne({'_id': ObjectId(deleted_seaweed_item['_id'])},
|
||||||
{'$set': {'status': 1, 'update_date': update_date}}, upsert=False)
|
# {'$set': {'status': 1, 'update_date': update_date}}, upsert=False)
|
||||||
actions.append(action)
|
# actions.append(action)
|
||||||
if len(actions) == 10000:
|
# if len(actions) == 10000:
|
||||||
seaweed_didata_conn.bulk_write(actions)
|
# seaweed_didata_conn.bulk_write(actions)
|
||||||
actions.clear()
|
# actions.clear()
|
||||||
|
#
|
||||||
if len(actions) > 0:
|
# if len(actions) > 0:
|
||||||
seaweed_didata_conn.bulk_write(actions)
|
# seaweed_didata_conn.bulk_write(actions)
|
||||||
actions.clear()
|
# actions.clear()
|
||||||
log.info(city + "-" + type + "-同步完成")
|
# log.info(city + "-" + type + "-同步完成")
|
||||||
|
#
|
||||||
|
#
|
||||||
if type == 'all':
|
# if type == 'all':
|
||||||
sync_district_office("district")
|
# sync_district_office("district")
|
||||||
sync_district_office("office")
|
# sync_district_office("office")
|
||||||
else:
|
# else:
|
||||||
sync_district_office(type)
|
# sync_district_office(type)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|||||||
@@ -1,59 +1,59 @@
|
|||||||
from airflow.providers.docker.operators.docker import DockerOperator
|
# from airflow.providers.docker.operators.docker import DockerOperator
|
||||||
from airflow.providers.cncf.kubernetes.operators.kubernetes_pod import KubernetesPodOperator
|
# from airflow.providers.cncf.kubernetes.operators.kubernetes_pod import KubernetesPodOperator
|
||||||
import pendulum
|
# import pendulum
|
||||||
from airflow import DAG
|
# from airflow import DAG
|
||||||
from docker.types import Mount
|
# from docker.types import Mount
|
||||||
from kubernetes.client import models as k8s
|
# from kubernetes.client import models as k8s
|
||||||
|
#
|
||||||
with DAG(
|
# with DAG(
|
||||||
dag_id="comm_add_dag",
|
# dag_id="comm_add_dag",
|
||||||
# 每月20日1点整分运行
|
# # 每月20日1点整分运行
|
||||||
schedule="0 1 20 * *",
|
# schedule="0 1 20 * *",
|
||||||
start_date=pendulum.datetime(2023, 5, 8, tz="Asia/Shanghai"),
|
# start_date=pendulum.datetime(2023, 5, 8, tz="Asia/Shanghai"),
|
||||||
catchup=True,
|
# catchup=True,
|
||||||
description="小区自动化入库"
|
# description="小区自动化入库"
|
||||||
) as dag:
|
# ) as dag:
|
||||||
# k = KubernetesPodOperator(
|
# # k = KubernetesPodOperator(
|
||||||
# name="comm-add",
|
# # name="comm-add",
|
||||||
|
# # image="192.168.0.19:9012/comm-add:1.0.1",
|
||||||
|
# # cmds=["bash", "-cx"],
|
||||||
|
# # arguments=["echo", "10"],
|
||||||
|
# # labels={"foo": "bar"},
|
||||||
|
# # task_id="comm_add",
|
||||||
|
# # do_xcom_push=True,
|
||||||
|
# # )
|
||||||
|
# # k.dry_run()
|
||||||
|
#
|
||||||
|
# production_task = KubernetesPodOperator(namespace='airflow-plus',
|
||||||
|
# # image="my-production-job:release-1.0.1", <-- old release
|
||||||
# image="192.168.0.19:9012/comm-add:1.0.1",
|
# image="192.168.0.19:9012/comm-add:1.0.1",
|
||||||
# cmds=["bash", "-cx"],
|
# image_pull_policy="Always",
|
||||||
# arguments=["echo", "10"],
|
# image_pull_secrets=[k8s.V1LocalObjectReference("nexus-registry-secret")],
|
||||||
# labels={"foo": "bar"},
|
# cmds=["python", "main.py"],
|
||||||
|
# arguments=["--city", '{{dag_run.conf["city"] if "city" in dag_run.conf else "all"}}'],
|
||||||
|
# name="comm_add",
|
||||||
# task_id="comm_add",
|
# task_id="comm_add",
|
||||||
# do_xcom_push=True,
|
# get_logs=True
|
||||||
# )
|
# )
|
||||||
# k.dry_run()
|
#
|
||||||
|
# production_task
|
||||||
production_task = KubernetesPodOperator(namespace='airflow-plus',
|
# # t1 = DockerOperator(
|
||||||
# image="my-production-job:release-1.0.1", <-- old release
|
# # # 刚才定义的conn id
|
||||||
image="192.168.0.19:9012/comm-add:1.0.1",
|
# # docker_conn_id="docker_repo",
|
||||||
image_pull_policy="Always",
|
# # # WebServer中点击Admin -> Providers -> Docker对应的Version,如果是auto,可能会报错
|
||||||
image_pull_secrets=[k8s.V1LocalObjectReference("nexus-registry-secret")],
|
# # api_version="2.2.0",
|
||||||
cmds=["python", "main.py"],
|
# # auto_remove=True,
|
||||||
arguments=["--city", '{{dag_run.conf["city"] if "city" in dag_run.conf else "all"}}'],
|
# # docker_url='unix://var/run/docker.sock',
|
||||||
name="comm_add",
|
# # network_mode='bridge',
|
||||||
task_id="comm_add",
|
# # image='192.168.0.19:9012/comm-add:1.0.1',
|
||||||
get_logs=True
|
# # # 临沂为我们的传参,python代码中, 镜像中部分代码
|
||||||
)
|
# # # @ click.command()
|
||||||
|
# # # @ click.option('--city', default="all", help='要计算的城市')
|
||||||
production_task
|
# # #command='python main.py --city {{dag_run.conf["city"] if "city" in dag_run.conf}} else all',
|
||||||
# t1 = DockerOperator(
|
# # command='echo "this is a test message shown from within the container',
|
||||||
# # 刚才定义的conn id
|
# # mounts=[
|
||||||
# docker_conn_id="docker_repo",
|
# # Mount(source="/var/run/docker.sock", target="/var/run/docker.sock", type="bind")
|
||||||
# # WebServer中点击Admin -> Providers -> Docker对应的Version,如果是auto,可能会报错
|
# # ],
|
||||||
# api_version="2.2.0",
|
# # task_id='comm_add'
|
||||||
# auto_remove=True,
|
# # )
|
||||||
# docker_url='unix://var/run/docker.sock',
|
# # t1
|
||||||
# network_mode='bridge',
|
|
||||||
# image='192.168.0.19:9012/comm-add:1.0.1',
|
|
||||||
# # 临沂为我们的传参,python代码中, 镜像中部分代码
|
|
||||||
# # @ click.command()
|
|
||||||
# # @ click.option('--city', default="all", help='要计算的城市')
|
|
||||||
# #command='python main.py --city {{dag_run.conf["city"] if "city" in dag_run.conf}} else all',
|
|
||||||
# command='echo "this is a test message shown from within the container',
|
|
||||||
# mounts=[
|
|
||||||
# Mount(source="/var/run/docker.sock", target="/var/run/docker.sock", type="bind")
|
|
||||||
# ],
|
|
||||||
# task_id='comm_add'
|
|
||||||
# )
|
|
||||||
# t1
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
@@ -6,7 +6,7 @@ with DAG(
|
|||||||
dag_id="community_summary_dag",
|
dag_id="community_summary_dag",
|
||||||
# 每月2日1点整分运行
|
# 每月2日1点整分运行
|
||||||
schedule="0 1 2 * *",
|
schedule="0 1 2 * *",
|
||||||
start_date=pendulum.datetime(2023, 3, 16, tz="Asia/Shanghai"),
|
start_date=pendulum.datetime(2026, 8, 16, tz="Asia/Shanghai"),
|
||||||
catchup=True,
|
catchup=True,
|
||||||
description="地址输出信息分类数据定时更新"
|
description="地址输出信息分类数据定时更新"
|
||||||
) as dag:
|
) as dag:
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
with DAG(
|
# with DAG(
|
||||||
dag_id="didata_sync_dag",
|
# dag_id="didata_sync_dag",
|
||||||
# 每月28日3点整分运行
|
# # 每月28日3点整分运行
|
||||||
schedule="0 3 28 * *",
|
# schedule="0 3 28 * *",
|
||||||
start_date=pendulum.datetime(2023, 3, 17, tz="Asia/Shanghai"),
|
# start_date=pendulum.datetime(2023, 3, 17, tz="Asia/Shanghai"),
|
||||||
catchup=True,
|
# catchup=True,
|
||||||
description="地数相关数据同步type: district或office, 不填默认同步全部"
|
# description="地数相关数据同步type: district或office, 不填默认同步全部"
|
||||||
) as dag:
|
# ) as dag:
|
||||||
t1 = BashOperator(
|
# t1 = BashOperator(
|
||||||
task_id='didata_sync_dag',
|
# task_id='didata_sync_dag',
|
||||||
bash_command='python /opt/airflow/dags/repo/dags/business/business/didata_sync.py {{dag_run.conf["type"] if "type" in dag_run.conf}}',
|
# bash_command='python /opt/airflow/dags/repo/dags/business/business/didata_sync.py {{dag_run.conf["type"] if "type" in dag_run.conf}}',
|
||||||
)
|
# )
|
||||||
t1
|
# t1
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
|
import pendulum
|
||||||
|
from airflow import DAG
|
||||||
|
|
||||||
|
with DAG(
|
||||||
|
dag_id="sync_es_price_to_mongo_dag",
|
||||||
|
# 每月3日凌晨2点整执行(在大部分上游爬取和ES清洗完毕后进行数据同步归档)
|
||||||
|
schedule="0 2 3 * *",
|
||||||
|
start_date=pendulum.datetime(2026, 8, 16, tz="Asia/Shanghai"),
|
||||||
|
catchup=False,
|
||||||
|
description="每月定时把 ES 206 上的 community 均价数据同步到 85 Mongo 的 average_statistics 表"
|
||||||
|
) as dag:
|
||||||
|
|
||||||
|
sync_es_price_to_mongo = BashOperator(
|
||||||
|
task_id='sync_es_price_to_mongo',
|
||||||
|
bash_command='python /opt/airflow/dags/repo/dags/business/business/community/sync_es_price_to_mongo.py {{dag_run.conf["month"] if "month" in dag_run.conf else ""}}',
|
||||||
|
)
|
||||||
@@ -1,12 +1,19 @@
|
|||||||
"""
|
"""
|
||||||
第一步: 将百度经纬度转为高德经纬度(只需跑批一次即可) TODO
|
第一步: 将百度经纬度转为高德经纬度(只需跑批一次即可) TODO
|
||||||
"""
|
"""
|
||||||
|
import os
|
||||||
|
# 1. 尝试环境变量兼容
|
||||||
|
os.environ["ELASTIC_CLIENT_APIVERSIONING"] = "0"
|
||||||
|
|
||||||
from goojia_utils import DIDATA_DEV_ELASTIC_CLIENT, threads, geohashutils, areautils
|
from goojia_utils import DIDATA_DEV_ELASTIC_CLIENT, threads, geohashutils, areautils
|
||||||
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__)
|
||||||
|
|
||||||
|
# ================== 🛡️ 安全运行入口 ==================
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
flag = False
|
flag = False
|
||||||
for province in areautils.get_all_province():
|
for province in areautils.get_all_province():
|
||||||
print(f"开始处理{province}数据")
|
print(f"开始处理{province}数据")
|
||||||
@@ -35,12 +42,14 @@ for province in areautils.get_all_province():
|
|||||||
})
|
})
|
||||||
if len(df) == 0:
|
if len(df) == 0:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
def deal_location(item):
|
def deal_location(item):
|
||||||
if pd.isna(item['location']):
|
if pd.isna(item['location']):
|
||||||
return item
|
return item
|
||||||
gd_location = geohashutils.bd_to_gd(item['location']['lon'], item['location']['lat'])
|
gd_location = geohashutils.bd_to_gd(item['location']['lon'], item['location']['lat'])
|
||||||
item['gaode_location'] = {'lon': gd_location[0], 'lat': gd_location[1]}
|
item['gaode_location'] = {'lon': gd_location[0], 'lat': gd_location[1]}
|
||||||
return item
|
return item
|
||||||
|
|
||||||
my_df = threads.process_dataframe_multithread(df, deal_location, num_threads=100)
|
my_df = threads.process_dataframe_multithread(df, deal_location, num_threads=100)
|
||||||
|
|
||||||
actions = list()
|
actions = list()
|
||||||
@@ -59,6 +68,7 @@ for province in areautils.get_all_province():
|
|||||||
actions.append(action)
|
actions.append(action)
|
||||||
if len(actions) == 5000:
|
if len(actions) == 5000:
|
||||||
for success, info in helpers.parallel_bulk(
|
for success, info in helpers.parallel_bulk(
|
||||||
|
# 此时这里的底层 elastic_client 将自动套用强行重置后的 JSON 请求头
|
||||||
DIDATA_DEV_ELASTIC_CLIENT.elastic_client,
|
DIDATA_DEV_ELASTIC_CLIENT.elastic_client,
|
||||||
actions,
|
actions,
|
||||||
thread_count=5, # 并行线程数
|
thread_count=5, # 并行线程数
|
||||||
@@ -69,6 +79,7 @@ for province in areautils.get_all_province():
|
|||||||
count += len(actions)
|
count += len(actions)
|
||||||
print("更新:" + str(count))
|
print("更新:" + str(count))
|
||||||
actions.clear()
|
actions.clear()
|
||||||
|
|
||||||
if len(actions) > 0:
|
if len(actions) > 0:
|
||||||
helpers.bulk(DIDATA_DEV_ELASTIC_CLIENT.elastic_client, actions)
|
helpers.bulk(DIDATA_DEV_ELASTIC_CLIENT.elastic_client, actions)
|
||||||
count += len(actions)
|
count += len(actions)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
import datetime
|
import datetime
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
"""
|
"""
|
||||||
小区周边配套DAG
|
小区周边配套DAG
|
||||||
"""
|
"""
|
||||||
from airflow.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 {}
|
||||||
@@ -27,7 +31,6 @@ def choose_task(**context):
|
|||||||
return ['office_city_region_rent_calc', 'office_base_rent_calc']
|
return ['office_city_region_rent_calc', 'office_base_rent_calc']
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
with DAG(
|
with DAG(
|
||||||
dag_id="office_rent_dag",
|
dag_id="office_rent_dag",
|
||||||
# 每月25日1点运行
|
# 每月25日1点运行
|
||||||
@@ -41,7 +44,7 @@ with DAG(
|
|||||||
branch_task = BranchPythonOperator(
|
branch_task = BranchPythonOperator(
|
||||||
task_id='choose_branch',
|
task_id='choose_branch',
|
||||||
python_callable=choose_task,
|
python_callable=choose_task,
|
||||||
provide_context=True
|
# 🛡️ 已移除 provide_context=True,防止 Airflow 3.3.0 报错崩溃
|
||||||
)
|
)
|
||||||
# 任务1:城市区域租金计算
|
# 任务1:城市区域租金计算
|
||||||
t1 = BashOperator(
|
t1 = BashOperator(
|
||||||
@@ -51,8 +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
|
# 🛡️ 已移除 provide_context=True,防止 Airflow 3.3.0 报错崩溃
|
||||||
)
|
)
|
||||||
branch_task >> [t1, t2]
|
branch_task >> [t1, t2]
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,21 @@
|
|||||||
from airflow.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 {}
|
||||||
@@ -50,28 +58,28 @@ with DAG(
|
|||||||
branch_task = BranchPythonOperator(
|
branch_task = BranchPythonOperator(
|
||||||
task_id='choose_branch',
|
task_id='choose_branch',
|
||||||
python_callable=choose_task,
|
python_callable=choose_task,
|
||||||
provide_context=True
|
# 🛡️ 已安全移除 provide_context=True
|
||||||
)
|
)
|
||||||
|
|
||||||
# 任务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
|
||||||
)
|
)
|
||||||
|
|
||||||
# 第二个分支任务:t2 后判断是否继续
|
# 第二个分支任务:t2 后判断是否继续
|
||||||
branch_after_office = BranchPythonOperator(
|
branch_after_office = BranchPythonOperator(
|
||||||
task_id='choose_after_office',
|
task_id='choose_after_office',
|
||||||
python_callable=choose_after_office,
|
python_callable=choose_after_office,
|
||||||
provide_context=True
|
# 🛡️ 已安全移除 provide_context=True
|
||||||
)
|
)
|
||||||
|
|
||||||
# 跳过标记(office 模式结束点)
|
# 跳过标记(office 模式结束点)
|
||||||
|
|||||||
@@ -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')
|
||||||
|
|||||||
+38
-11
@@ -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,27 +74,40 @@ 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} 均价计算完毕!")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
yearmonth = sys.argv[1] if len(sys.argv) > 1 else ''
|
yearmonth = sys.argv[1] if len(sys.argv) > 1 else ''
|
||||||
|
|
||||||
if yearmonth == '':
|
if yearmonth == '':
|
||||||
|
|||||||
@@ -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,6 +124,7 @@ def calc(city, year_month):
|
|||||||
log.info(f"均价补充完毕!")
|
log.info(f"均价补充完毕!")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
yearmonth = sys.argv[1] if len(sys.argv) > 1 else ''
|
yearmonth = sys.argv[1] if len(sys.argv) > 1 else ''
|
||||||
|
|
||||||
if yearmonth == '':
|
if yearmonth == '':
|
||||||
|
|||||||
+40
-11
@@ -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,26 +76,39 @@ 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} 均价计算完毕!")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
yearmonth = sys.argv[1] if len(sys.argv) > 1 else ''
|
yearmonth = sys.argv[1] if len(sys.argv) > 1 else ''
|
||||||
|
|
||||||
if yearmonth == '':
|
if yearmonth == '':
|
||||||
|
|||||||
@@ -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
|
||||||
|
)
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
小区周边配套DAG
|
小区周边配套DAG
|
||||||
"""
|
"""
|
||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
|
|
||||||
import pendulum
|
import pendulum
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
区域房价指数DAG
|
区域房价指数DAG
|
||||||
"""
|
"""
|
||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
|
|
||||||
import pendulum
|
import pendulum
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
小区房价指数DAG
|
小区房价指数DAG
|
||||||
"""
|
"""
|
||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
|
|
||||||
import pendulum
|
import pendulum
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
小区周边配套DAG
|
小区周边配套DAG
|
||||||
"""
|
"""
|
||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
|
|
||||||
import pendulum
|
import pendulum
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
小区周边配套DAG
|
小区周边配套DAG
|
||||||
"""
|
"""
|
||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
|
|
||||||
import pendulum
|
import pendulum
|
||||||
|
|
||||||
|
|||||||
@@ -1,37 +0,0 @@
|
|||||||
import requests
|
|
||||||
import ssl
|
|
||||||
import datetime
|
|
||||||
import urllib3
|
|
||||||
from goojia_utils import nextcloudutils, dingutils
|
|
||||||
|
|
||||||
# 禁用 InsecureRequestWarning
|
|
||||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
|
||||||
|
|
||||||
# 获取当前日期
|
|
||||||
current_date = datetime.datetime.now()
|
|
||||||
# 计算前一日的日期
|
|
||||||
previous_date = current_date - datetime.timedelta(days=1)
|
|
||||||
# 格式化日期
|
|
||||||
formatted_date = previous_date.strftime("%Y.%m.%d")
|
|
||||||
|
|
||||||
data = {
|
|
||||||
"parentCode": "001.002",
|
|
||||||
"dateRange": formatted_date + "," + formatted_date
|
|
||||||
}
|
|
||||||
headers = {
|
|
||||||
"Accept": "*/*",
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJhY2NvdW50IjoiYWlyZmxvdyIsImV4cCI6MTMxMzM5NDE2MzQwNDYxLCJvcmdDb2RlIjoiMDAxLjAwMSIsInJvbGVzIjpbIm5vcm1hbCJdLCJ1c2VySWQiOiIxODg5ODc0MDc4MTgxODMwNjU2IiwidXNlcm5hbWUiOiLlrprml7bku7vliqEifQ.SvD42b8XGlxYe_0dBr215ZgxR9aBdsipaySceZuuWR6g5cHelU5oc-dRtK63b0CMoN07BSvh2XYdlIzQ92ngOA"
|
|
||||||
}
|
|
||||||
|
|
||||||
ret = requests.post(url='https://api.fangjia.com/exportStatistics', json=data, headers=headers, verify=False)
|
|
||||||
#ret = requests.post(url='http://127.0.0.1:8080/exportStatistics', json=data, headers=headers, verify=False)
|
|
||||||
|
|
||||||
nextcloud_aim_file_path = '共享/AI估价/农行统计'
|
|
||||||
file_path = "AI估价农行" + formatted_date + ".xlsx"
|
|
||||||
with open(file_path, 'wb') as file:
|
|
||||||
# 将字节流写入文件
|
|
||||||
file.write(ret.content)
|
|
||||||
nextcloudutils.up_to_nextcloud(file_path, nextcloud_aim_file_path + "/" + "AI估价农行" + formatted_date + ".xlsx")
|
|
||||||
|
|
||||||
dingutils.send_text("【AI估价】农行" + formatted_date + "统计完成, 请点击 https://nextcloud.fangjia.com/s/WK9MzWwH5kjwMBB 查看", "f4f3b03c35c67d097f70affa27e7d47d7a1b6c0eed2438f4d8aa654834419a0b")
|
|
||||||
@@ -1,249 +0,0 @@
|
|||||||
"""
|
|
||||||
统计城市 区域 价格涨跌幅
|
|
||||||
"""
|
|
||||||
import logging
|
|
||||||
import pandas as pd
|
|
||||||
from sqlalchemy import create_engine
|
|
||||||
from goojia_utils import dateutils
|
|
||||||
import datetime
|
|
||||||
import os
|
|
||||||
pathAll = "/home/airflow/data/cityPrice"
|
|
||||||
if not os.path.exists(pathAll):
|
|
||||||
os.makedirs(pathAll)
|
|
||||||
# 创建数据库引擎
|
|
||||||
engine235 = create_engine("postgresql+psycopg2://postgres:Goojia123456@192.168.0.235:5433/fangjia?client_encoding=utf8",
|
|
||||||
echo=False)
|
|
||||||
pd.set_option('mode.chained_assignment', None)
|
|
||||||
year_month_day = dateutils.format_date(datetime.datetime.now())
|
|
||||||
# 执行SQL查询获取城市价格数据
|
|
||||||
city_sql = "SELECT DISTINCT urbn_nm FROM price_stat.avm_city_price"
|
|
||||||
city_names_set = set(pd.read_sql(city_sql, engine235)['urbn_nm'])
|
|
||||||
city_names = list(city_names_set)
|
|
||||||
# 假设这是你的pgsql数据
|
|
||||||
all_city_data = pd.DataFrame()
|
|
||||||
# 执行SQL查询获取区域价格数据
|
|
||||||
region_sql = "SELECT DISTINCT urbn_nm,gxda_admndiv_nm FROM price_stat.avm_district_price"
|
|
||||||
region_data = pd.read_sql(region_sql, engine235)
|
|
||||||
city_data_useinregion = pd.DataFrame()
|
|
||||||
# 假设这是你的pgsql数据
|
|
||||||
all_region_data = pd.DataFrame()
|
|
||||||
|
|
||||||
def up_to_nextcloud(aim_file_name,aim_file_path):
|
|
||||||
"""
|
|
||||||
上传统计信息至nextcloud
|
|
||||||
"""
|
|
||||||
from nextcloud import NextCloud
|
|
||||||
NEXTCLOUD_URL = "https://nextcloud.fangjia.com"
|
|
||||||
NEXTCLOUD_USERNAME = "shenjian@fangjia.com"
|
|
||||||
NEXTCLOUD_PASSWORD = "goojia123456"
|
|
||||||
nxc = NextCloud(endpoint=NEXTCLOUD_URL, user=NEXTCLOUD_USERNAME, password=NEXTCLOUD_PASSWORD, json_output=True)
|
|
||||||
nxc.upload_file(aim_file_name, aim_file_path)
|
|
||||||
def city_increase(city_names, all_city_data):
|
|
||||||
global city_data_useinregion # 声明为全局变量
|
|
||||||
# 遍历城市列表,对每个城市进行查询
|
|
||||||
for city in city_names:
|
|
||||||
query = f"SELECT urbn_nm as 城市, gujiabds_clc_yrmo_val as 月份, gujia_bds_clc_avprc as 估家计算均价, gujia_bds_urbn_avprc as 估家城市均价 FROM price_stat.avm_city_price WHERE urbn_nm = '{city}'"
|
|
||||||
city_data = pd.read_sql(query, engine235)
|
|
||||||
|
|
||||||
if city_data.empty:
|
|
||||||
continue
|
|
||||||
|
|
||||||
# 复制一份原始的日期列,用于计算涨跌幅时保持原始数据不变
|
|
||||||
city_data['original_date'] = city_data['月份']
|
|
||||||
|
|
||||||
# 将日期列转换为日期类型
|
|
||||||
city_data['月份'] = pd.to_datetime(city_data['月份'], format='%Y%m')
|
|
||||||
|
|
||||||
# 对价格数据按照月份排序
|
|
||||||
city_data.sort_values(by='月份', inplace=True)
|
|
||||||
|
|
||||||
# 计算涨跌幅
|
|
||||||
city_data['涨跌幅'] = city_data['估家计算均价'].diff() / city_data['估家计算均价'].shift(1) * 100
|
|
||||||
|
|
||||||
# 计算涨跌幅,并保留两位小数,展示为百分比形式
|
|
||||||
price_change = city_data['估家计算均价'].pct_change() * 100
|
|
||||||
city_data['涨跌幅'] = (price_change[price_change != 0].fillna(0).round(2).astype(str) + '%').replace('0.0%', '')
|
|
||||||
|
|
||||||
# 将原始日期列替换为计算涨跌幅后的日期列
|
|
||||||
city_data['月份'] = city_data['original_date']
|
|
||||||
|
|
||||||
# 删除临时列
|
|
||||||
city_data.drop(columns=['original_date'], inplace=True)
|
|
||||||
|
|
||||||
# 将城市数据添加到总的数据中
|
|
||||||
all_city_data = pd.concat([all_city_data, city_data], ignore_index=True)
|
|
||||||
city_data_useinregion = all_city_data
|
|
||||||
return all_city_data
|
|
||||||
|
|
||||||
|
|
||||||
def city_missing():
|
|
||||||
df = city_increase(city_names, all_city_data)
|
|
||||||
df['月份1'] = df['月份']
|
|
||||||
# 将日期字符串转换为日期时间对象
|
|
||||||
df["月份"] = pd.to_datetime(df["月份"], format="%Y%m")
|
|
||||||
|
|
||||||
# 获取当前时间
|
|
||||||
current_time = pd.Timestamp.today().replace(hour=0, minute=0, second=0, microsecond=0)
|
|
||||||
|
|
||||||
# 计算前一年到上月的时间范围
|
|
||||||
one_year_ago = current_time - pd.DateOffset(years=1, days=current_time.day - 1)
|
|
||||||
last_month = current_time - pd.DateOffset(months=1, days=current_time.day - 1)
|
|
||||||
|
|
||||||
# 创建一个包含所有可能月份的日期范围
|
|
||||||
all_months = pd.date_range(start=one_year_ago, end=last_month, freq="MS")
|
|
||||||
|
|
||||||
# 获取每个城市缺失的月份
|
|
||||||
missing_months = []
|
|
||||||
for city, group in df.groupby("城市"):
|
|
||||||
available_months = group["月份"]
|
|
||||||
missing = all_months.difference(available_months)
|
|
||||||
if len(missing) > 0:
|
|
||||||
missing_str = ",".join([m.strftime("%Y%m") for m in missing])
|
|
||||||
missing_months.append({"城市": city, "缺失月份": missing_str})
|
|
||||||
if len(missing_months) > 0:
|
|
||||||
# 创建DataFrame来存储结果
|
|
||||||
missing_df = pd.DataFrame(missing_months)
|
|
||||||
path = pathAll+'/城市价格数据缺失'+year_month_day+'.xlsx'
|
|
||||||
missing_df.to_excel(path, index=False)
|
|
||||||
logging.info(f"城市价格缺失数据已写入Excel文件:{path}")
|
|
||||||
|
|
||||||
cloudPath = '共享/统计/城市区域涨跌幅/' + '城市价格数据缺失'+year_month_day+'.xlsx'
|
|
||||||
up_to_nextcloud(path, cloudPath)
|
|
||||||
logging.info(f"区域涨跌幅数据Excel文件已经上传到云盘")
|
|
||||||
|
|
||||||
# print(missing_df)
|
|
||||||
df['月份'] = df['月份1']
|
|
||||||
# 删除月份1列
|
|
||||||
df.drop(columns=['月份1'], inplace=True)
|
|
||||||
output_path = pathAll+'/城市价格涨跌幅'+year_month_day+'.xlsx'
|
|
||||||
df.to_excel(output_path, index=False)
|
|
||||||
logging.info(f"城市涨跌幅数据已写入Excel文件:{output_path}")
|
|
||||||
|
|
||||||
cloudPath = '共享/统计/城市区域涨跌幅/' + '城市价格涨跌幅'+year_month_day+'.xlsx'
|
|
||||||
up_to_nextcloud(output_path, cloudPath)
|
|
||||||
logging.info(f"区域涨跌幅数据Excel文件已经上传到云盘")
|
|
||||||
|
|
||||||
|
|
||||||
def region_increase(region_data, all_region_data):
|
|
||||||
# 遍历区域列表,对每个区域进行查询
|
|
||||||
for index, row in region_data.iterrows():
|
|
||||||
city = row['urbn_nm']
|
|
||||||
region = row['gxda_admndiv_nm']
|
|
||||||
query = f"SELECT urbn_nm as 城市, gxda_admndiv_nm as 区域, gujiabds_clc_yrmo_val as 月份, gujia_bds_clc_avprc as 估家计算均价, gujia_bds_urbn_avprc as 估家城市均价 FROM price_stat.avm_district_price WHERE urbn_nm = '{city}' AND gxda_admndiv_nm = '{region}'"
|
|
||||||
region_data = pd.read_sql(query, engine235)
|
|
||||||
|
|
||||||
if region_data.empty:
|
|
||||||
continue
|
|
||||||
|
|
||||||
# 复制一份原始的日期列,用于计算涨跌幅时保持原始数据不变
|
|
||||||
region_data['original_date'] = region_data['月份']
|
|
||||||
|
|
||||||
# 将日期列转换为日期类型
|
|
||||||
region_data['月份'] = pd.to_datetime(region_data['月份'], format='%Y%m')
|
|
||||||
|
|
||||||
# 对价格数据按照月份排序
|
|
||||||
region_data.sort_values(by='月份', inplace=True)
|
|
||||||
|
|
||||||
# 计算涨跌幅
|
|
||||||
region_data['涨跌幅'] = region_data['估家计算均价'].diff() / region_data['估家计算均价'].shift(1) * 100
|
|
||||||
|
|
||||||
# 计算涨跌幅,并保留两位小数,展示为百分比形式
|
|
||||||
price_change = region_data['估家计算均价'].pct_change() * 100
|
|
||||||
region_data['涨跌幅'] = (price_change[price_change != 0].fillna(0).round(2).astype(str) + '%').replace('0.0%',
|
|
||||||
'')
|
|
||||||
|
|
||||||
# 将原始日期列替换为计算涨跌幅后的日期列
|
|
||||||
region_data['月份'] = region_data['original_date']
|
|
||||||
|
|
||||||
# 删除临时列
|
|
||||||
region_data.drop(columns=['original_date'], inplace=True)
|
|
||||||
|
|
||||||
# 将区域数据添加到总的数据中
|
|
||||||
all_region_data = pd.concat([all_region_data, region_data], ignore_index=True)
|
|
||||||
|
|
||||||
return all_region_data
|
|
||||||
|
|
||||||
|
|
||||||
# 城市价个和区域价格比较
|
|
||||||
def add_price_comparison_by_month(region_data):
|
|
||||||
# 遍历区域数据,比较城市和区域的价格,并添加比值超过3倍的情况到区域数据中
|
|
||||||
for index, row in region_data.iterrows():
|
|
||||||
city = row['城市']
|
|
||||||
region = row['区域']
|
|
||||||
region_month = row['月份']
|
|
||||||
region_price = row['估家计算均价']
|
|
||||||
city_data = city_data_useinregion
|
|
||||||
# 获取城市对应月份的价格
|
|
||||||
city_price_row = city_data[(city_data['城市'] == city) & (city_data['月份'] == region_month)]
|
|
||||||
if city_price_row.empty:
|
|
||||||
continue
|
|
||||||
city_price = city_price_row['估家城市均价'].iloc[0]
|
|
||||||
|
|
||||||
# 比较价格并计算比值
|
|
||||||
price_ratio = max(city_price, region_price) / min(city_price, region_price)
|
|
||||||
|
|
||||||
# 如果比值超过3倍,将结果添加到区域数据中
|
|
||||||
if price_ratio > 3:
|
|
||||||
region_data.loc[index, '城市区域价格比值超3倍'] = price_ratio
|
|
||||||
|
|
||||||
return region_data
|
|
||||||
|
|
||||||
|
|
||||||
def region_missing():
|
|
||||||
df = region_increase(region_data, all_region_data)
|
|
||||||
df['月份1'] = df['月份']
|
|
||||||
# 将日期字符串转换为日期时间对象
|
|
||||||
df["月份"] = pd.to_datetime(df["月份"], format="%Y%m")
|
|
||||||
|
|
||||||
# 获取当前时间
|
|
||||||
current_time = pd.Timestamp.today().replace(hour=0, minute=0, second=0, microsecond=0)
|
|
||||||
|
|
||||||
# 计算前一年到上月的时间范围
|
|
||||||
one_year_ago = current_time - pd.DateOffset(years=1, days=current_time.day - 1)
|
|
||||||
last_month = current_time - pd.DateOffset(months=1, days=current_time.day - 1)
|
|
||||||
|
|
||||||
# 创建一个包含所有可能月份的日期范围
|
|
||||||
all_months = pd.date_range(start=one_year_ago, end=last_month, freq="MS")
|
|
||||||
|
|
||||||
# 获取每个城市-区域组合缺失的月份
|
|
||||||
missing_months = []
|
|
||||||
for (city, region), group in df.groupby(["城市", "区域"]):
|
|
||||||
available_months = group["月份"]
|
|
||||||
missing = all_months.difference(available_months)
|
|
||||||
if len(missing) > 0:
|
|
||||||
missing_str = ",".join([m.strftime("%Y%m") for m in missing])
|
|
||||||
missing_months.append({"城市": city, "区域": region, "缺失月份": missing_str})
|
|
||||||
|
|
||||||
if missing_months:
|
|
||||||
# 创建DataFrame来存储结果
|
|
||||||
missing_df = pd.DataFrame(missing_months)
|
|
||||||
path = pathAll+'/区域价格数据缺失'+year_month_day+'.xlsx'
|
|
||||||
missing_df.to_excel(path, index=False)
|
|
||||||
logging.info(f"区域价格缺失数据已写入Excel文件:{path}")
|
|
||||||
cloudPath = '共享/统计/城市区域涨跌幅/' + '区域价格数据缺失' + year_month_day + '.xlsx'
|
|
||||||
up_to_nextcloud(path, cloudPath)
|
|
||||||
logging.info(f"区域价格缺失数据Excel文件已经上传到云盘")
|
|
||||||
|
|
||||||
# 如果区域在 missing_df 中,则将 df 中的该区域数据删除
|
|
||||||
for city, region in zip(missing_df['城市'], missing_df['区域']):
|
|
||||||
df = df[(df['城市'] != city) | (df['区域'] != region)]
|
|
||||||
|
|
||||||
df['月份'] = df['月份1']
|
|
||||||
# 删除月份1列
|
|
||||||
df.drop(columns=['月份1'], inplace=True)
|
|
||||||
|
|
||||||
# 添加价格比值超过3倍的列
|
|
||||||
# print(city_data_useinregion)
|
|
||||||
df = add_price_comparison_by_month(df)
|
|
||||||
|
|
||||||
output_path = pathAll+'/区域价格涨跌幅'+year_month_day+'.xlsx'
|
|
||||||
df.to_excel(output_path, index=False)
|
|
||||||
logging.info(f"区域涨跌幅数据已写入Excel文件:{output_path}")
|
|
||||||
|
|
||||||
cloudPath = '共享/统计/城市区域涨跌幅/' + '区域价格涨跌幅'+year_month_day+'.xlsx'
|
|
||||||
up_to_nextcloud(output_path, cloudPath)
|
|
||||||
logging.info(f"区域涨跌幅数据Excel文件已经上传到云盘")
|
|
||||||
|
|
||||||
|
|
||||||
city_missing()
|
|
||||||
region_missing()
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
import logging
|
|
||||||
import pandas as pd
|
|
||||||
from sqlalchemy import create_engine
|
|
||||||
|
|
||||||
# 创建数据库引擎
|
|
||||||
engine235 = create_engine("postgresql+psycopg2://postgres:Goojia123456@192.168.0.235:5433/fangjia?client_encoding=utf8",
|
|
||||||
echo=False)
|
|
||||||
|
|
||||||
# 执行SQL查询获取区域价格数据
|
|
||||||
region_sql = "SELECT DISTINCT urbn_nm,gxda_admndiv_nm FROM price_stat.avm_district_price_copy1"
|
|
||||||
region_data = pd.read_sql(region_sql, engine235)
|
|
||||||
|
|
||||||
# 假设这是你的pgsql数据
|
|
||||||
all_region_data = pd.DataFrame()
|
|
||||||
pd.set_option('mode.chained_assignment', None)
|
|
||||||
|
|
||||||
def region_increase(region_data, all_region_data):
|
|
||||||
# 遍历区域列表,对每个区域进行查询
|
|
||||||
for index, row in region_data.iterrows():
|
|
||||||
city = row['urbn_nm']
|
|
||||||
region = row['gxda_admndiv_nm']
|
|
||||||
query = f"SELECT urbn_nm as 城市, gxda_admndiv_nm as 区域, gujiabds_clc_yrmo_val as 月份, gujia_bds_clc_avprc as 估家计算均价, gujia_bds_urbn_avprc as 估家城市均价 FROM price_stat.avm_district_price_copy1 WHERE urbn_nm = '{city}' AND gxda_admndiv_nm = '{region}'"
|
|
||||||
region_data = pd.read_sql(query, engine235)
|
|
||||||
|
|
||||||
if region_data.empty:
|
|
||||||
continue
|
|
||||||
|
|
||||||
# 复制一份原始的日期列,用于计算涨跌幅时保持原始数据不变
|
|
||||||
region_data['original_date'] = region_data['月份']
|
|
||||||
|
|
||||||
# 将日期列转换为日期类型
|
|
||||||
region_data['月份'] = pd.to_datetime(region_data['月份'], format='%Y%m')
|
|
||||||
|
|
||||||
# 对价格数据按照月份排序
|
|
||||||
region_data.sort_values(by='月份', inplace=True)
|
|
||||||
|
|
||||||
# 计算涨跌幅
|
|
||||||
region_data['涨跌幅'] = region_data['估家计算均价'].diff() / region_data['估家计算均价'].shift(1) * 100
|
|
||||||
|
|
||||||
# 计算涨跌幅,并保留两位小数,展示为百分比形式
|
|
||||||
price_change = region_data['估家计算均价'].pct_change() * 100
|
|
||||||
region_data['涨跌幅'] = (price_change[price_change != 0].fillna(0).round(2).astype(str) + '%').replace('0.0%', '')
|
|
||||||
|
|
||||||
# 将原始日期列替换为计算涨跌幅后的日期列
|
|
||||||
region_data['月份'] = region_data['original_date']
|
|
||||||
|
|
||||||
# 删除临时列
|
|
||||||
region_data.drop(columns=['original_date'], inplace=True)
|
|
||||||
|
|
||||||
# 将区域数据添加到总的数据中
|
|
||||||
all_region_data = pd.concat([all_region_data, region_data], ignore_index=True)
|
|
||||||
|
|
||||||
return all_region_data
|
|
||||||
|
|
||||||
def region_missing():
|
|
||||||
df = region_increase(region_data, all_region_data)
|
|
||||||
df['月份1'] = df['月份']
|
|
||||||
# 将日期字符串转换为日期时间对象
|
|
||||||
df["月份"] = pd.to_datetime(df["月份"], format="%Y%m")
|
|
||||||
|
|
||||||
# 获取当前时间
|
|
||||||
current_time = pd.Timestamp.today().replace(hour=0, minute=0, second=0, microsecond=0)
|
|
||||||
|
|
||||||
# 计算前一年到上月的时间范围
|
|
||||||
one_year_ago = current_time - pd.DateOffset(years=1, days=current_time.day - 1)
|
|
||||||
last_month = current_time - pd.DateOffset(months=1, days=current_time.day - 1)
|
|
||||||
|
|
||||||
# 创建一个包含所有可能月份的日期范围
|
|
||||||
all_months = pd.date_range(start=one_year_ago, end=last_month, freq="MS")
|
|
||||||
|
|
||||||
# 获取每个城市-区域组合缺失的月份
|
|
||||||
missing_months = []
|
|
||||||
for (city, region), group in df.groupby(["城市", "区域"]):
|
|
||||||
available_months = group["月份"]
|
|
||||||
missing = all_months.difference(available_months)
|
|
||||||
if len(missing) > 0:
|
|
||||||
missing_str = ",".join([m.strftime("%Y%m") for m in missing])
|
|
||||||
missing_months.append({"城市": city, "区域": region, "缺失月份": missing_str})
|
|
||||||
|
|
||||||
if missing_months:
|
|
||||||
# 创建DataFrame来存储结果
|
|
||||||
missing_df = pd.DataFrame(missing_months)
|
|
||||||
path = 'E:\\goojia\\file\\excel文件\\airflow\\missing_region.xlsx'
|
|
||||||
missing_df.to_excel(path, index=False)
|
|
||||||
|
|
||||||
# 如果区域在 missing_df 中,则将 df 中的该区域数据删除
|
|
||||||
for city, region in zip(missing_df['城市'], missing_df['区域']):
|
|
||||||
df = df[(df['城市'] != city) | (df['区域'] != region)]
|
|
||||||
|
|
||||||
df['月份'] = df['月份1']
|
|
||||||
# 删除月份1列
|
|
||||||
df.drop(columns=['月份1'], inplace=True)
|
|
||||||
output_path = 'E:\\goojia\\file\\excel文件\\airflow\\all_region_price_with_change.xlsx'
|
|
||||||
df.to_excel(output_path, index=False)
|
|
||||||
logging.info(f"区域涨跌幅数据已写入Excel文件:{output_path}")
|
|
||||||
|
|
||||||
region_missing()
|
|
||||||
@@ -1,263 +0,0 @@
|
|||||||
"""
|
|
||||||
小区数量 租金 均价 及 覆盖率统计
|
|
||||||
"""
|
|
||||||
|
|
||||||
from goojia_utils import MAIN_MONGO_CLIENT, dateutils, ClickHouseClient, ElasticSearchClient, commutils
|
|
||||||
import pandas as pd
|
|
||||||
import os
|
|
||||||
import logging
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
server_area_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'server_area')
|
|
||||||
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
|
||||||
district_stat_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'district_stat')
|
|
||||||
sqmetre_rent_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'sqmetre_rent')
|
|
||||||
clickHouseClient = ClickHouseClient(host="192.168.0.216", database='fangjia_stat')
|
|
||||||
deal_price_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'deal_price')
|
|
||||||
|
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.206')
|
|
||||||
|
|
||||||
city_df = pd.DataFrame(list(server_area_conn.find({}, {'city_grade': 1, 'display': 1})))
|
|
||||||
city_df = city_df.rename(columns={'city_grade': 'city_level', 'display': 'city'})
|
|
||||||
city_df = city_df[city_df['city_level'] != 0]
|
|
||||||
# 昆玉无小区
|
|
||||||
city_df = city_df[city_df['city'] != '昆玉'].reset_index(drop=True)
|
|
||||||
|
|
||||||
seaweed_df = pd.DataFrame(
|
|
||||||
list(seaweed_conn.find({'cat': 'district', 'status': 0},
|
|
||||||
{'city': 1, 'region': 1, 'name': 1, 'alias': 1, 'addr_alias': 1})
|
|
||||||
.batch_size(100000)))
|
|
||||||
|
|
||||||
path = "/opt/airflow/dags/repo/dags/business/business/community/data"
|
|
||||||
|
|
||||||
aim_path = "/home/airflow/data/stat"
|
|
||||||
if not os.path.exists(aim_path):
|
|
||||||
os.makedirs(aim_path)
|
|
||||||
|
|
||||||
ret_df = pd.read_excel(path + '/财力评级分布情况20221215.xlsx')
|
|
||||||
|
|
||||||
for index, item in city_df.iterrows():
|
|
||||||
city = item['city']
|
|
||||||
region_df = seaweed_df[(seaweed_df['city'] == city)].copy()
|
|
||||||
alias_count = 0
|
|
||||||
addr_count = 0
|
|
||||||
seaweed_count = 0
|
|
||||||
# 楼盘数量
|
|
||||||
city_df.loc[index, 'community_count'] = len(region_df)
|
|
||||||
if len(region_df) == 0:
|
|
||||||
log.error(f"该城市{city}小区数量为0")
|
|
||||||
for index1, item1 in region_df.iterrows():
|
|
||||||
flag = True
|
|
||||||
if type(item1['alias']) == list:
|
|
||||||
if len(item1['alias']) > 0:
|
|
||||||
alias_count += len(item1['alias'])
|
|
||||||
seaweed_count += 1
|
|
||||||
flag = False
|
|
||||||
if type(item1['addr_alias']) == list:
|
|
||||||
if len(item1['addr_alias']) > 0:
|
|
||||||
addr_count += len(item1['addr_alias'])
|
|
||||||
if len(item1['addr_alias']) > 0 and flag is True:
|
|
||||||
seaweed_count += 1
|
|
||||||
# 楼盘别名总数
|
|
||||||
city_df.loc[index, 'alias_count'] = alias_count
|
|
||||||
# 地址别名数量
|
|
||||||
city_df.loc[index, 'addr_alias_count'] = addr_count
|
|
||||||
# 有别名小区量【存在楼盘别名或地址别名】
|
|
||||||
city_df.loc[index, 'exist_alias_community_count'] = seaweed_count
|
|
||||||
|
|
||||||
# 【已过期】
|
|
||||||
# #### 1. 小区数量
|
|
||||||
# result_df = pd.DataFrame(list(seaweed_conn.aggregate([
|
|
||||||
# {'$match': {'cat': 'district', 'status': 0}},
|
|
||||||
# {'$group': {'_id': "$city", 'community_count': {'$sum': 1}}}])))
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# result_df = result_df.rename(columns={'_id': 'city'})
|
|
||||||
# df = pd.merge(result_df, city_df, how='right', on='city')
|
|
||||||
# df.fillna(0, inplace=True)
|
|
||||||
|
|
||||||
# 有别名小区量 该方式统计不准,可能存在[]情况也算了
|
|
||||||
# alias_df = pd.DataFrame(list(seaweed_conn.aggregate([
|
|
||||||
# {'$match': {'cat': 'district', 'status': 0, 'mapping_alias': {'$ne': None}}},
|
|
||||||
# {'$group': {'_id': "$city", 'alias_count': {'$sum': 1}}}])))
|
|
||||||
# alias_df = alias_df.rename(columns={'_id': 'city'})
|
|
||||||
# df = pd.merge(df, alias_df, how='left', on=['city'])
|
|
||||||
|
|
||||||
df = city_df.copy()
|
|
||||||
|
|
||||||
# 主力户型
|
|
||||||
main_type_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
|
||||||
{'$match': {'cat': 'district', 'status': 0, 'main_type': {'$ne': None}}},
|
|
||||||
{'$group': {'_id': "$city", 'main_type_count': {'$sum': 1}}}])))
|
|
||||||
main_type_count = main_type_count.rename(columns={'_id': 'city'})
|
|
||||||
df = pd.merge(df, main_type_count, how='left', on=['city'])
|
|
||||||
df['main_type_coverage'] = df['main_type_count'] * 100 / df['community_count']
|
|
||||||
# 主力面积
|
|
||||||
main_type_area_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
|
||||||
{'$match': {'cat': 'district', 'status': 0, 'main_type_area': {'$ne': None}}},
|
|
||||||
{'$group': {'_id': "$city", 'main_type_area_count': {'$sum': 1}}}])))
|
|
||||||
main_type_area_count = main_type_area_count.rename(columns={'_id': 'city'})
|
|
||||||
df = pd.merge(df, main_type_area_count, how='left', on=['city'])
|
|
||||||
df['main_type_area_coverage'] = df['main_type_area_count'] * 100 / df['community_count']
|
|
||||||
# 物业类型
|
|
||||||
estate_type_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
|
||||||
{'$match': {'cat': 'district', 'status': 0, 'estate_type2': {'$ne': None}}},
|
|
||||||
{'$group': {'_id': "$city", 'estate_type_count': {'$sum': 1}}}])))
|
|
||||||
estate_type_count = estate_type_count.rename(columns={'_id': 'city'})
|
|
||||||
df = pd.merge(df, estate_type_count, how='left', on=['city'])
|
|
||||||
df['estate_type_coverage'] = df['estate_type_count'] * 100 / df['community_count']
|
|
||||||
# 建成年代
|
|
||||||
finish_building_date_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
|
||||||
{'$match': {'cat': 'district', 'status': 0, 'finish_building_date': {'$ne': None}}},
|
|
||||||
{'$group': {'_id': "$city", 'finish_building_date_count': {'$sum': 1}}}])))
|
|
||||||
finish_building_date_count = finish_building_date_count.rename(columns={'_id': 'city'})
|
|
||||||
df = pd.merge(df, finish_building_date_count, how='left', on=['city'])
|
|
||||||
df['finish_building_date_coverage'] = df['finish_building_date_count'] * 100 / df['community_count']
|
|
||||||
# 占地面积
|
|
||||||
all_area_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
|
||||||
{'$match': {'cat': 'district', 'status': 0, 'all_area': {'$ne': None}}},
|
|
||||||
{'$group': {'_id': "$city", 'all_area_count': {'$sum': 1}}}])))
|
|
||||||
all_area_count = all_area_count.rename(columns={'_id': 'city'})
|
|
||||||
df = pd.merge(df, all_area_count, how='left', on=['city'])
|
|
||||||
df['all_area_coverage'] = df['all_area_count'] * 100 / df['community_count']
|
|
||||||
# 建筑面积
|
|
||||||
build_area_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
|
||||||
{'$match': {'cat': 'district', 'status': 0, 'build_area': {'$ne': None}}},
|
|
||||||
{'$group': {'_id': "$city", 'build_area_count': {'$sum': 1}}}])))
|
|
||||||
build_area_count = build_area_count.rename(columns={'_id': 'city'})
|
|
||||||
df = pd.merge(df, build_area_count, how='left', on=['city'])
|
|
||||||
df['build_area_coverage'] = df['build_area_count'] * 100 / df['community_count']
|
|
||||||
|
|
||||||
# 绿化率
|
|
||||||
greening_rate_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
|
||||||
{'$match': {'cat': 'district', 'status': 0, 'virescence_percent': {'$ne': None}}},
|
|
||||||
{'$group': {'_id': "$city", 'greening_rate_count': {'$sum': 1}}}])))
|
|
||||||
greening_rate_count = greening_rate_count.rename(columns={'_id': 'city'})
|
|
||||||
df = pd.merge(df, greening_rate_count, how='left', on=['city'])
|
|
||||||
df['greening_rate_coverage'] = df['greening_rate_count'] * 100 / df['community_count']
|
|
||||||
# 容积率
|
|
||||||
volume_rate_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
|
||||||
{'$match': {'cat': 'district', 'status': 0, 'cubage_percent': {'$ne': None}}},
|
|
||||||
{'$group': {'_id': "$city", 'volume_rate_count': {'$sum': 1}}}])))
|
|
||||||
volume_rate_count = volume_rate_count.rename(columns={'_id': 'city'})
|
|
||||||
df = pd.merge(df, volume_rate_count, how='left', on=['city'])
|
|
||||||
df['volume_rate_coverage'] = df['volume_rate_count'] * 100 / df['community_count']
|
|
||||||
|
|
||||||
# 户均总价
|
|
||||||
df['total_price_count'] = None
|
|
||||||
# 物业费
|
|
||||||
df['estate_charge_count'] = None
|
|
||||||
# 人均消费
|
|
||||||
df['avg_cost_count'] = None
|
|
||||||
# 财力评级
|
|
||||||
df['consumption_rating_count'] = None
|
|
||||||
for index, item in df.iterrows():
|
|
||||||
curr_city = item['city']
|
|
||||||
sql = f"select count(*) from community_summary where city='{curr_city}' and total_price>0 "
|
|
||||||
num = es206_client.search_by_sql(sql)['hits']['total']['value']
|
|
||||||
df.loc[index, 'total_price_count'] = num
|
|
||||||
|
|
||||||
sql = f"select count(*) from community_summary where city='{curr_city}' and estate_charge>0 "
|
|
||||||
estate_charge_num = es206_client.search_by_sql(sql)['hits']['total']['value']
|
|
||||||
df.loc[index, 'estate_charge_count'] = estate_charge_num
|
|
||||||
|
|
||||||
sql = f"select count(*) from community_summary where city='{curr_city}' and avg_cost>0 "
|
|
||||||
avg_cost_count = es206_client.search_by_sql(sql)['hits']['total']['value']
|
|
||||||
df.loc[index, 'avg_cost_count'] = avg_cost_count
|
|
||||||
|
|
||||||
sql = f"select count(*) from community_summary where city='{curr_city}' and consumption_rating>0 "
|
|
||||||
consumption_rating_num = es206_client.search_by_sql(sql)['hits']['total']['value']
|
|
||||||
df.loc[index, 'consumption_rating_count'] = consumption_rating_num
|
|
||||||
|
|
||||||
df['total_price_coverage'] = df['total_price_count'] * 100 / df['community_count']
|
|
||||||
df['consumption_rating_coverage'] = df['consumption_rating_count'] * 100 / df['community_count']
|
|
||||||
df['estate_charge_coverage'] = df['estate_charge_count'] * 100 / df['community_count']
|
|
||||||
df['avg_cost_coverage'] = df['avg_cost_count'] * 100 / df['community_count']
|
|
||||||
|
|
||||||
##### 2. 近一年成交量
|
|
||||||
|
|
||||||
# 小区别名升级为单独df
|
|
||||||
actions = list()
|
|
||||||
for index, item in seaweed_df.iterrows():
|
|
||||||
if type(item['alias']) == list:
|
|
||||||
for name in item['alias']:
|
|
||||||
actions.append({'_id': item['_id'], 'city': item['city'], 'name': name, 'region': item['region']})
|
|
||||||
alias_df = pd.DataFrame(actions)
|
|
||||||
seaweed_alias_df = pd.concat([seaweed_df[['_id', 'city', 'region', 'name']], alias_df])
|
|
||||||
deal_price_df = pd.DataFrame(list(deal_price_conn.find(
|
|
||||||
{'trade_date': {'$gte': dateutils.add_months(dateutils.datetime.datetime.now(), days=-365)}},
|
|
||||||
{'city': 1, 'region': 1, 'district_name': 1, '_id': 0}).batch_size(10000)))
|
|
||||||
deal_price_df = deal_price_df.rename(columns={'district_name': 'name'})
|
|
||||||
deal_price_seaweed_df = pd.merge(deal_price_df, seaweed_alias_df, how='left', on=['city', 'region', 'name'])
|
|
||||||
# 剔除没有配到的小区
|
|
||||||
deal_price_seaweed_notnull_df = deal_price_seaweed_df.dropna(subset=['_id'])
|
|
||||||
deal_price_seaweed_notnull_df.loc[:, 'one_year_deal'] = deal_price_seaweed_notnull_df.groupby(['city'])[
|
|
||||||
'city'].transform('size')
|
|
||||||
deal_price_half_year_df = deal_price_seaweed_notnull_df[['city', 'one_year_deal']].drop_duplicates(keep='first')
|
|
||||||
df = pd.merge(df, deal_price_half_year_df, how='left', on=['city'])
|
|
||||||
|
|
||||||
# #### 2. 均价数量
|
|
||||||
|
|
||||||
avg_price_df = commutils.get_avg_price()
|
|
||||||
rent_price_df = commutils.get_rent_price()
|
|
||||||
|
|
||||||
avg_price_df['avg_price_count'] = avg_price_df.groupby(by=['city'])['_id'].transform('count')
|
|
||||||
rent_price_df['sqmetre_rent_count'] = rent_price_df.groupby(by=['city'])['_id'].transform('count')
|
|
||||||
|
|
||||||
avg_price_df = avg_price_df[['city', 'avg_price_count']].drop_duplicates(keep='first')
|
|
||||||
rent_price_df = rent_price_df[['city', 'sqmetre_rent_count']].drop_duplicates(keep='first')
|
|
||||||
|
|
||||||
df = pd.merge(df, avg_price_df, how='left', on=['city'])
|
|
||||||
df = pd.merge(df, rent_price_df, how='left', on=['city'])
|
|
||||||
|
|
||||||
df['avg_price_coverage'] = df['avg_price_count'] * 100 / df['community_count']
|
|
||||||
df['sqmetre_rent_coverage'] = df['sqmetre_rent_count'] * 100 / df['community_count']
|
|
||||||
|
|
||||||
|
|
||||||
df.fillna(0, inplace=True)
|
|
||||||
|
|
||||||
df['community_count'] = df['community_count'].astype(int)
|
|
||||||
df['avg_price_count'] = df['avg_price_count'].astype(int)
|
|
||||||
df['sqmetre_rent_count'] = df['sqmetre_rent_count'].astype(int)
|
|
||||||
df['one_year_deal'] = df['one_year_deal'].astype(int)
|
|
||||||
df['alias_count'] = df['alias_count'].astype(int)
|
|
||||||
df['addr_alias_count'] = df['addr_alias_count'].astype(int)
|
|
||||||
df['exist_alias_community_count'] = df['exist_alias_community_count'].astype(int)
|
|
||||||
|
|
||||||
df = df.round({'avg_price_coverage': 2, 'sqmetre_rent_coverage': 2, 'main_type_coverage': 2, 'main_type_area_coverage': 2, 'total_price_coverage': 2, 'estate_type_coverage': 2,
|
|
||||||
'finish_building_date_coverage': 2, 'all_area_coverage': 2, 'build_area_coverage': 2, 'estate_charge_coverage': 2, 'avg_cost_coverage': 2, 'consumption_rating_coverage': 2, 'greening_rate_coverage': 2, 'volume_rate_coverage': 2})
|
|
||||||
df = df[['city', 'community_count', 'city_level', 'avg_price_coverage', 'sqmetre_rent_coverage', 'alias_count', 'addr_alias_count',
|
|
||||||
'exist_alias_community_count', 'one_year_deal', 'main_type_coverage', 'main_type_area_coverage', 'total_price_coverage', 'estate_type_coverage',
|
|
||||||
'finish_building_date_coverage', 'all_area_coverage', 'build_area_coverage', 'estate_charge_coverage', 'avg_cost_coverage', 'consumption_rating_coverage', 'greening_rate_coverage', 'volume_rate_coverage']]
|
|
||||||
|
|
||||||
df['weekend'] = dateutils.datetime.datetime.now()
|
|
||||||
# 删除本日生成的重复数据,防止手工点击生成
|
|
||||||
clickHouseClient.execute(
|
|
||||||
"ALTER TABLE fangjia_stat.community_coverage_stat DELETE WHERE weekend = toDate('" + dateutils.format_date(dateutils.datetime.datetime.now(), '%Y-%m-%d') + "')")
|
|
||||||
clickHouseClient.to_sql(df, table='community_coverage_stat', if_exists='insert', order_by='weekend')
|
|
||||||
|
|
||||||
# 上传至nextcloud
|
|
||||||
ret_df = pd.merge(ret_df, df, how='left', on=['city'])
|
|
||||||
del ret_df['是否合理']
|
|
||||||
ret_df = ret_df.rename(columns={'city': '城市', 'city_level': '城市级别', 'community_count': "楼盘数量", "alias_count": "别名数量", "addr_alias_count": "地址别名数量", "exist_alias_community_count": "有别名覆盖小区数量",
|
|
||||||
'estate_type_coverage': '物业类型覆盖率', 'avg_price_coverage': '均价覆盖率', 'sqmetre_rent_coverage': '平米租金覆盖率', 'total_price_coverage': '户均总价覆盖率', 'estate_charge_coverage': '物业费覆盖率', 'avg_cost_coverage': '人均消费覆盖率', 'main_type_coverage': '主力户型覆盖率', 'main_type_area_coverage': '主力面积覆盖率', 'finish_building_date_coverage': '建成年代覆盖率', 'all_area_coverage': '占地面积覆盖率', 'build_area_coverage': '建筑面积覆盖率', 'consumption_rating_coverage': '财力评级覆盖率', 'greening_rate_coverage': '绿化率覆盖率', 'volume_rate_coverage': '容积率覆盖率'})
|
|
||||||
output_date = dateutils.format_date(dateutils.datetime.datetime.now())
|
|
||||||
aim_file_name = aim_path + "/" + output_date + '覆盖率统计.xlsx'
|
|
||||||
ret_df.to_excel(aim_file_name, index=False)
|
|
||||||
|
|
||||||
# https://nextcloud.fangjia.com/s/3aw663fy9BbiBeLji'bie
|
|
||||||
|
|
||||||
def up_to_nextcloud():
|
|
||||||
"""
|
|
||||||
上传统计信息至nextcloud
|
|
||||||
"""
|
|
||||||
from nextcloud import NextCloud
|
|
||||||
NEXTCLOUD_URL = "https://nextcloud.fangjia.com"
|
|
||||||
NEXTCLOUD_USERNAME = "shenjian@fangjia.com"
|
|
||||||
NEXTCLOUD_PASSWORD = "goojia123456"
|
|
||||||
aim_file_path = '共享/统计/常用覆盖率统计' + output_date + '.xlsx'
|
|
||||||
nxc = NextCloud(endpoint=NEXTCLOUD_URL, user=NEXTCLOUD_USERNAME, password=NEXTCLOUD_PASSWORD, json_output=True)
|
|
||||||
nxc.upload_file(aim_file_name, aim_file_path)
|
|
||||||
|
|
||||||
up_to_nextcloud()
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
"""
|
|
||||||
小区周边1公里交通地铁入库业务逻辑
|
|
||||||
"""
|
|
||||||
import datetime
|
|
||||||
import logging
|
|
||||||
import pandas as pd
|
|
||||||
from goojia_utils import MAIN_MONGO_CLIENT
|
|
||||||
from goojia_utils import dateutils
|
|
||||||
from sklearn.mixture import GaussianMixture
|
|
||||||
from pymongo import InsertOne, DeleteMany, ReplaceOne, UpdateOne
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
district_stat_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'district_stat')
|
|
||||||
district_analy_data_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'district_analy_data')
|
|
||||||
server_area_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'server_area')
|
|
||||||
weekend = list(district_stat_conn.find().sort([("weekend", -1)]).limit(1))[0]['weekend']
|
|
||||||
level_map = {"1": "S", "2": "A", "3": "B", "4": "C", "5": "D"}
|
|
||||||
logger.info(f"开始计算楼盘评级 weekend:{dateutils.format_date(weekend, '%Y-%m-%d')}")
|
|
||||||
for server_area in server_area_conn.find({'display': {'$ne': '全国'}}, {"display": 1}):
|
|
||||||
city = server_area["display"]
|
|
||||||
data = pd.DataFrame(
|
|
||||||
district_stat_conn.find({"city": city, "weekend": weekend},
|
|
||||||
{"_id": 0, "region": 1, "district_name": 1, "avg_price": 1}))
|
|
||||||
if "avg_price" not in data or len(data['avg_price'].unique()) < 5:
|
|
||||||
continue
|
|
||||||
data['city'] = city
|
|
||||||
logger.info(f"开始计算{city}楼盘评级 weekend:{dateutils.format_date(weekend, '%Y-%m-%d')}")
|
|
||||||
# 高斯混合模型
|
|
||||||
gmm = GaussianMixture(n_components=5, covariance_type='tied', max_iter=200, n_init=10).fit(
|
|
||||||
data[["avg_price"]])
|
|
||||||
data.loc[:, 'cluster'] = gmm.predict(data[["avg_price"]])
|
|
||||||
data.loc[:, 'price_mean_cluster'] = data.groupby('cluster')["avg_price"].transform('mean')
|
|
||||||
data.loc[:, "target"] = data['price_mean_cluster'].rank(method='dense', ascending=False).astype(int)
|
|
||||||
data = data.drop(columns=['cluster', 'price_mean_cluster'], axis=1)
|
|
||||||
data["community_rating"] = data['target'].apply(lambda x: level_map[str(x)])
|
|
||||||
opts = []
|
|
||||||
for item in data.to_dict('records'):
|
|
||||||
opts.append(UpdateOne({"city": city, "region": item["region"], "district_name": item["district_name"]},
|
|
||||||
{"$set": {"community_rating": item["community_rating"]}}, upsert=True
|
|
||||||
))
|
|
||||||
# 按照每 1000 条分割 updates 列表
|
|
||||||
batch_size = 1000
|
|
||||||
batches = [opts[i:i + batch_size] for i in range(0, len(opts), batch_size)]
|
|
||||||
# 逐个批次执行批量更新操作
|
|
||||||
cnt = 0
|
|
||||||
for batch in batches:
|
|
||||||
cnt = cnt + 1
|
|
||||||
logger.info(f"{city}楼盘评级更新数据库, 进度:{cnt}/{len(batches)}")
|
|
||||||
result = district_analy_data_conn.bulk_write(batch)
|
|
||||||
print(f"当前批次更新的文档数量: {result.modified_count}")
|
|
||||||
logger.info(f"楼盘评级计算结束{dateutils.format_date(datetime.datetime.utcnow(), '%Y-%m-%d')}")
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
|
||||||
import pendulum
|
|
||||||
from airflow import DAG
|
|
||||||
|
|
||||||
with DAG(
|
|
||||||
dag_id="increase_decrease_city_region_dag",
|
|
||||||
# 每月的最后一天运行
|
|
||||||
schedule="0 10 L * *",
|
|
||||||
start_date=pendulum.datetime(2024, 5, 30, tz="Asia/Shanghai"),
|
|
||||||
description="城市区域涨跌幅数据统计",
|
|
||||||
catchup=True
|
|
||||||
) as dag:
|
|
||||||
t1 = BashOperator(
|
|
||||||
task_id='increase_decrease_city_region',
|
|
||||||
bash_command='python /opt/airflow/dags/repo/dags/stat/cityPrice/increase_decrease_city_region.py',
|
|
||||||
)
|
|
||||||
t1
|
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import requests
|
||||||
|
import ssl
|
||||||
|
import datetime
|
||||||
|
import urllib3
|
||||||
|
from goojia_utils import nextcloudutils, dingutils
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# 禁用 InsecureRequestWarning
|
||||||
|
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||||
|
|
||||||
|
# 获取当前日期
|
||||||
|
current_date = datetime.datetime.now()
|
||||||
|
# 计算前一日的日期
|
||||||
|
previous_date = current_date - datetime.timedelta(days=1)
|
||||||
|
# 格式化日期
|
||||||
|
formatted_date = previous_date.strftime("%Y.%m.%d")
|
||||||
|
|
||||||
|
data = {
|
||||||
|
"parentCode": "001.002",
|
||||||
|
"dateRange": formatted_date + "," + formatted_date
|
||||||
|
}
|
||||||
|
headers = {
|
||||||
|
"Accept": "*/*",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJhY2NvdW50IjoiYWlyZmxvdyIsImV4cCI6MTMxMzM5NDE2MzQwNDYxLCJvcmdDb2RlIjoiMDAxLjAwMSIsInJvbGVzIjpbIm5vcm1hbCJdLCJ1c2VySWQiOiIxODg5ODc0MDc4MTgxODMwNjU2IiwidXNlcm5hbWUiOiLlrprml7bku7vliqEifQ.SvD42b8XGlxYe_0dBr215ZgxR9aBdsipaySceZuuWR6g5cHelU5oc-dRtK63b0CMoN07BSvh2XYdlIzQ92ngOA"
|
||||||
|
}
|
||||||
|
|
||||||
|
ret = requests.post(url='https://api.fangjia.com/exportStatistics', json=data, headers=headers, verify=False)
|
||||||
|
#ret = requests.post(url='http://127.0.0.1:8080/exportStatistics', json=data, headers=headers, verify=False)
|
||||||
|
|
||||||
|
nextcloud_aim_file_path = '共享/AI估价/农行统计'
|
||||||
|
file_path = "AI估价农行" + formatted_date + ".xlsx"
|
||||||
|
with open(file_path, 'wb') as file:
|
||||||
|
# 将字节流写入文件
|
||||||
|
file.write(ret.content)
|
||||||
|
nextcloudutils.up_to_nextcloud(file_path, nextcloud_aim_file_path + "/" + "AI估价农行" + formatted_date + ".xlsx")
|
||||||
|
|
||||||
|
dingutils.send_text("【AI估价】农行" + formatted_date + "统计完成, 请点击 https://nextcloud.fangjia.com/s/WK9MzWwH5kjwMBB 查看", "f4f3b03c35c67d097f70affa27e7d47d7a1b6c0eed2438f4d8aa654834419a0b")
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
# """
|
||||||
|
# 统计城市 区域 价格涨跌幅
|
||||||
|
# """
|
||||||
|
# import logging
|
||||||
|
# import pandas as pd
|
||||||
|
# from sqlalchemy import create_engine
|
||||||
|
# from goojia_utils import dateutils
|
||||||
|
# import datetime
|
||||||
|
# import os
|
||||||
|
# pathAll = "/home/airflow/data/cityPrice"
|
||||||
|
# if not os.path.exists(pathAll):
|
||||||
|
# os.makedirs(pathAll)
|
||||||
|
# # 创建数据库引擎
|
||||||
|
# engine235 = create_engine("postgresql+psycopg2://postgres:Goojia123456@192.168.0.235:5433/fangjia?client_encoding=utf8",
|
||||||
|
# echo=False)
|
||||||
|
# pd.set_option('mode.chained_assignment', None)
|
||||||
|
# year_month_day = dateutils.format_date(datetime.datetime.now())
|
||||||
|
# # 执行SQL查询获取城市价格数据
|
||||||
|
# city_sql = "SELECT DISTINCT urbn_nm FROM price_stat.avm_city_price"
|
||||||
|
# city_names_set = set(pd.read_sql(city_sql, engine235)['urbn_nm'])
|
||||||
|
# city_names = list(city_names_set)
|
||||||
|
# # 假设这是你的pgsql数据
|
||||||
|
# all_city_data = pd.DataFrame()
|
||||||
|
# # 执行SQL查询获取区域价格数据
|
||||||
|
# region_sql = "SELECT DISTINCT urbn_nm,gxda_admndiv_nm FROM price_stat.avm_district_price"
|
||||||
|
# region_data = pd.read_sql(region_sql, engine235)
|
||||||
|
# city_data_useinregion = pd.DataFrame()
|
||||||
|
# # 假设这是你的pgsql数据
|
||||||
|
# all_region_data = pd.DataFrame()
|
||||||
|
#
|
||||||
|
# def up_to_nextcloud(aim_file_name,aim_file_path):
|
||||||
|
# """
|
||||||
|
# 上传统计信息至nextcloud
|
||||||
|
# """
|
||||||
|
# from nextcloud import NextCloud
|
||||||
|
# NEXTCLOUD_URL = "https://nextcloud.fangjia.com"
|
||||||
|
# NEXTCLOUD_USERNAME = "shenjian@fangjia.com"
|
||||||
|
# NEXTCLOUD_PASSWORD = "goojia123456"
|
||||||
|
# nxc = NextCloud(endpoint=NEXTCLOUD_URL, user=NEXTCLOUD_USERNAME, password=NEXTCLOUD_PASSWORD, json_output=True)
|
||||||
|
# nxc.upload_file(aim_file_name, aim_file_path)
|
||||||
|
# def city_increase(city_names, all_city_data):
|
||||||
|
# global city_data_useinregion # 声明为全局变量
|
||||||
|
# # 遍历城市列表,对每个城市进行查询
|
||||||
|
# for city in city_names:
|
||||||
|
# query = f"SELECT urbn_nm as 城市, gujiabds_clc_yrmo_val as 月份, gujia_bds_clc_avprc as 估家计算均价, gujia_bds_urbn_avprc as 估家城市均价 FROM price_stat.avm_city_price WHERE urbn_nm = '{city}'"
|
||||||
|
# city_data = pd.read_sql(query, engine235)
|
||||||
|
#
|
||||||
|
# if city_data.empty:
|
||||||
|
# continue
|
||||||
|
#
|
||||||
|
# # 复制一份原始的日期列,用于计算涨跌幅时保持原始数据不变
|
||||||
|
# city_data['original_date'] = city_data['月份']
|
||||||
|
#
|
||||||
|
# # 将日期列转换为日期类型
|
||||||
|
# city_data['月份'] = pd.to_datetime(city_data['月份'], format='%Y%m')
|
||||||
|
#
|
||||||
|
# # 对价格数据按照月份排序
|
||||||
|
# city_data.sort_values(by='月份', inplace=True)
|
||||||
|
#
|
||||||
|
# # 计算涨跌幅
|
||||||
|
# city_data['涨跌幅'] = city_data['估家计算均价'].diff() / city_data['估家计算均价'].shift(1) * 100
|
||||||
|
#
|
||||||
|
# # 计算涨跌幅,并保留两位小数,展示为百分比形式
|
||||||
|
# price_change = city_data['估家计算均价'].pct_change() * 100
|
||||||
|
# city_data['涨跌幅'] = (price_change[price_change != 0].fillna(0).round(2).astype(str) + '%').replace('0.0%', '')
|
||||||
|
#
|
||||||
|
# # 将原始日期列替换为计算涨跌幅后的日期列
|
||||||
|
# city_data['月份'] = city_data['original_date']
|
||||||
|
#
|
||||||
|
# # 删除临时列
|
||||||
|
# city_data.drop(columns=['original_date'], inplace=True)
|
||||||
|
#
|
||||||
|
# # 将城市数据添加到总的数据中
|
||||||
|
# all_city_data = pd.concat([all_city_data, city_data], ignore_index=True)
|
||||||
|
# city_data_useinregion = all_city_data
|
||||||
|
# return all_city_data
|
||||||
|
#
|
||||||
|
#
|
||||||
|
# def city_missing():
|
||||||
|
# df = city_increase(city_names, all_city_data)
|
||||||
|
# df['月份1'] = df['月份']
|
||||||
|
# # 将日期字符串转换为日期时间对象
|
||||||
|
# df["月份"] = pd.to_datetime(df["月份"], format="%Y%m")
|
||||||
|
#
|
||||||
|
# # 获取当前时间
|
||||||
|
# current_time = pd.Timestamp.today().replace(hour=0, minute=0, second=0, microsecond=0)
|
||||||
|
#
|
||||||
|
# # 计算前一年到上月的时间范围
|
||||||
|
# one_year_ago = current_time - pd.DateOffset(years=1, days=current_time.day - 1)
|
||||||
|
# last_month = current_time - pd.DateOffset(months=1, days=current_time.day - 1)
|
||||||
|
#
|
||||||
|
# # 创建一个包含所有可能月份的日期范围
|
||||||
|
# all_months = pd.date_range(start=one_year_ago, end=last_month, freq="MS")
|
||||||
|
#
|
||||||
|
# # 获取每个城市缺失的月份
|
||||||
|
# missing_months = []
|
||||||
|
# for city, group in df.groupby("城市"):
|
||||||
|
# available_months = group["月份"]
|
||||||
|
# missing = all_months.difference(available_months)
|
||||||
|
# if len(missing) > 0:
|
||||||
|
# missing_str = ",".join([m.strftime("%Y%m") for m in missing])
|
||||||
|
# missing_months.append({"城市": city, "缺失月份": missing_str})
|
||||||
|
# if len(missing_months) > 0:
|
||||||
|
# # 创建DataFrame来存储结果
|
||||||
|
# missing_df = pd.DataFrame(missing_months)
|
||||||
|
# path = pathAll+'/城市价格数据缺失'+year_month_day+'.xlsx'
|
||||||
|
# missing_df.to_excel(path, index=False)
|
||||||
|
# logging.info(f"城市价格缺失数据已写入Excel文件:{path}")
|
||||||
|
#
|
||||||
|
# cloudPath = '共享/统计/城市区域涨跌幅/' + '城市价格数据缺失'+year_month_day+'.xlsx'
|
||||||
|
# up_to_nextcloud(path, cloudPath)
|
||||||
|
# logging.info(f"区域涨跌幅数据Excel文件已经上传到云盘")
|
||||||
|
#
|
||||||
|
# # print(missing_df)
|
||||||
|
# df['月份'] = df['月份1']
|
||||||
|
# # 删除月份1列
|
||||||
|
# df.drop(columns=['月份1'], inplace=True)
|
||||||
|
# output_path = pathAll+'/城市价格涨跌幅'+year_month_day+'.xlsx'
|
||||||
|
# df.to_excel(output_path, index=False)
|
||||||
|
# logging.info(f"城市涨跌幅数据已写入Excel文件:{output_path}")
|
||||||
|
#
|
||||||
|
# cloudPath = '共享/统计/城市区域涨跌幅/' + '城市价格涨跌幅'+year_month_day+'.xlsx'
|
||||||
|
# up_to_nextcloud(output_path, cloudPath)
|
||||||
|
# logging.info(f"区域涨跌幅数据Excel文件已经上传到云盘")
|
||||||
|
#
|
||||||
|
#
|
||||||
|
# def region_increase(region_data, all_region_data):
|
||||||
|
# # 遍历区域列表,对每个区域进行查询
|
||||||
|
# for index, row in region_data.iterrows():
|
||||||
|
# city = row['urbn_nm']
|
||||||
|
# region = row['gxda_admndiv_nm']
|
||||||
|
# query = f"SELECT urbn_nm as 城市, gxda_admndiv_nm as 区域, gujiabds_clc_yrmo_val as 月份, gujia_bds_clc_avprc as 估家计算均价, gujia_bds_urbn_avprc as 估家城市均价 FROM price_stat.avm_district_price WHERE urbn_nm = '{city}' AND gxda_admndiv_nm = '{region}'"
|
||||||
|
# region_data = pd.read_sql(query, engine235)
|
||||||
|
#
|
||||||
|
# if region_data.empty:
|
||||||
|
# continue
|
||||||
|
#
|
||||||
|
# # 复制一份原始的日期列,用于计算涨跌幅时保持原始数据不变
|
||||||
|
# region_data['original_date'] = region_data['月份']
|
||||||
|
#
|
||||||
|
# # 将日期列转换为日期类型
|
||||||
|
# region_data['月份'] = pd.to_datetime(region_data['月份'], format='%Y%m')
|
||||||
|
#
|
||||||
|
# # 对价格数据按照月份排序
|
||||||
|
# region_data.sort_values(by='月份', inplace=True)
|
||||||
|
#
|
||||||
|
# # 计算涨跌幅
|
||||||
|
# region_data['涨跌幅'] = region_data['估家计算均价'].diff() / region_data['估家计算均价'].shift(1) * 100
|
||||||
|
#
|
||||||
|
# # 计算涨跌幅,并保留两位小数,展示为百分比形式
|
||||||
|
# price_change = region_data['估家计算均价'].pct_change() * 100
|
||||||
|
# region_data['涨跌幅'] = (price_change[price_change != 0].fillna(0).round(2).astype(str) + '%').replace('0.0%',
|
||||||
|
# '')
|
||||||
|
#
|
||||||
|
# # 将原始日期列替换为计算涨跌幅后的日期列
|
||||||
|
# region_data['月份'] = region_data['original_date']
|
||||||
|
#
|
||||||
|
# # 删除临时列
|
||||||
|
# region_data.drop(columns=['original_date'], inplace=True)
|
||||||
|
#
|
||||||
|
# # 将区域数据添加到总的数据中
|
||||||
|
# all_region_data = pd.concat([all_region_data, region_data], ignore_index=True)
|
||||||
|
#
|
||||||
|
# return all_region_data
|
||||||
|
#
|
||||||
|
#
|
||||||
|
# # 城市价个和区域价格比较
|
||||||
|
# def add_price_comparison_by_month(region_data):
|
||||||
|
# # 遍历区域数据,比较城市和区域的价格,并添加比值超过3倍的情况到区域数据中
|
||||||
|
# for index, row in region_data.iterrows():
|
||||||
|
# city = row['城市']
|
||||||
|
# region = row['区域']
|
||||||
|
# region_month = row['月份']
|
||||||
|
# region_price = row['估家计算均价']
|
||||||
|
# city_data = city_data_useinregion
|
||||||
|
# # 获取城市对应月份的价格
|
||||||
|
# city_price_row = city_data[(city_data['城市'] == city) & (city_data['月份'] == region_month)]
|
||||||
|
# if city_price_row.empty:
|
||||||
|
# continue
|
||||||
|
# city_price = city_price_row['估家城市均价'].iloc[0]
|
||||||
|
#
|
||||||
|
# # 比较价格并计算比值
|
||||||
|
# price_ratio = max(city_price, region_price) / min(city_price, region_price)
|
||||||
|
#
|
||||||
|
# # 如果比值超过3倍,将结果添加到区域数据中
|
||||||
|
# if price_ratio > 3:
|
||||||
|
# region_data.loc[index, '城市区域价格比值超3倍'] = price_ratio
|
||||||
|
#
|
||||||
|
# return region_data
|
||||||
|
#
|
||||||
|
#
|
||||||
|
# def region_missing():
|
||||||
|
# df = region_increase(region_data, all_region_data)
|
||||||
|
# df['月份1'] = df['月份']
|
||||||
|
# # 将日期字符串转换为日期时间对象
|
||||||
|
# df["月份"] = pd.to_datetime(df["月份"], format="%Y%m")
|
||||||
|
#
|
||||||
|
# # 获取当前时间
|
||||||
|
# current_time = pd.Timestamp.today().replace(hour=0, minute=0, second=0, microsecond=0)
|
||||||
|
#
|
||||||
|
# # 计算前一年到上月的时间范围
|
||||||
|
# one_year_ago = current_time - pd.DateOffset(years=1, days=current_time.day - 1)
|
||||||
|
# last_month = current_time - pd.DateOffset(months=1, days=current_time.day - 1)
|
||||||
|
#
|
||||||
|
# # 创建一个包含所有可能月份的日期范围
|
||||||
|
# all_months = pd.date_range(start=one_year_ago, end=last_month, freq="MS")
|
||||||
|
#
|
||||||
|
# # 获取每个城市-区域组合缺失的月份
|
||||||
|
# missing_months = []
|
||||||
|
# for (city, region), group in df.groupby(["城市", "区域"]):
|
||||||
|
# available_months = group["月份"]
|
||||||
|
# missing = all_months.difference(available_months)
|
||||||
|
# if len(missing) > 0:
|
||||||
|
# missing_str = ",".join([m.strftime("%Y%m") for m in missing])
|
||||||
|
# missing_months.append({"城市": city, "区域": region, "缺失月份": missing_str})
|
||||||
|
#
|
||||||
|
# if missing_months:
|
||||||
|
# # 创建DataFrame来存储结果
|
||||||
|
# missing_df = pd.DataFrame(missing_months)
|
||||||
|
# path = pathAll+'/区域价格数据缺失'+year_month_day+'.xlsx'
|
||||||
|
# missing_df.to_excel(path, index=False)
|
||||||
|
# logging.info(f"区域价格缺失数据已写入Excel文件:{path}")
|
||||||
|
# cloudPath = '共享/统计/城市区域涨跌幅/' + '区域价格数据缺失' + year_month_day + '.xlsx'
|
||||||
|
# up_to_nextcloud(path, cloudPath)
|
||||||
|
# logging.info(f"区域价格缺失数据Excel文件已经上传到云盘")
|
||||||
|
#
|
||||||
|
# # 如果区域在 missing_df 中,则将 df 中的该区域数据删除
|
||||||
|
# for city, region in zip(missing_df['城市'], missing_df['区域']):
|
||||||
|
# df = df[(df['城市'] != city) | (df['区域'] != region)]
|
||||||
|
#
|
||||||
|
# df['月份'] = df['月份1']
|
||||||
|
# # 删除月份1列
|
||||||
|
# df.drop(columns=['月份1'], inplace=True)
|
||||||
|
#
|
||||||
|
# # 添加价格比值超过3倍的列
|
||||||
|
# # print(city_data_useinregion)
|
||||||
|
# df = add_price_comparison_by_month(df)
|
||||||
|
#
|
||||||
|
# output_path = pathAll+'/区域价格涨跌幅'+year_month_day+'.xlsx'
|
||||||
|
# df.to_excel(output_path, index=False)
|
||||||
|
# logging.info(f"区域涨跌幅数据已写入Excel文件:{output_path}")
|
||||||
|
#
|
||||||
|
# cloudPath = '共享/统计/城市区域涨跌幅/' + '区域价格涨跌幅'+year_month_day+'.xlsx'
|
||||||
|
# up_to_nextcloud(output_path, cloudPath)
|
||||||
|
# logging.info(f"区域涨跌幅数据Excel文件已经上传到云盘")
|
||||||
|
#
|
||||||
|
#
|
||||||
|
# city_missing()
|
||||||
|
# region_missing()
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
"""
|
||||||
|
小区数量 租金 均价 及 覆盖率统计
|
||||||
|
"""
|
||||||
|
|
||||||
|
from goojia_utils import MAIN_MONGO_CLIENT, dateutils, ClickHouseClient, ElasticSearchClient, commutils
|
||||||
|
import pandas as pd
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
# ================== 辅助上传函数(全局定义,供 main 调用) ==================
|
||||||
|
|
||||||
|
def up_to_nextcloud():
|
||||||
|
"""
|
||||||
|
上传统计信息至nextcloud
|
||||||
|
"""
|
||||||
|
from nextcloud import NextCloud
|
||||||
|
NEXTCLOUD_URL = "https://nextcloud.fangjia.com"
|
||||||
|
NEXTCLOUD_USERNAME = "shenjian@fangjia.com"
|
||||||
|
NEXTCLOUD_PASSWORD = "goojia123456"
|
||||||
|
# 使用运行时生成的 output_date 和 aim_file_name 全局变量
|
||||||
|
aim_file_path = '共享/统计/常用覆盖率统计' + output_date + '.xlsx'
|
||||||
|
nxc = NextCloud(endpoint=NEXTCLOUD_URL, user=NEXTCLOUD_USERNAME, password=NEXTCLOUD_PASSWORD, json_output=True)
|
||||||
|
nxc.upload_file(aim_file_name, aim_file_path)
|
||||||
|
|
||||||
|
|
||||||
|
# ================== 🛡️ 安全运行入口 ==================
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# 1. 延迟初始化数据库连接(避开 Airflow 进程的加载期)
|
||||||
|
server_area_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'server_area')
|
||||||
|
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
||||||
|
district_stat_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'district_stat')
|
||||||
|
sqmetre_rent_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'sqmetre_rent')
|
||||||
|
clickHouseClient = ClickHouseClient(host="192.168.0.216", database='fangjia_stat')
|
||||||
|
deal_price_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'deal_price')
|
||||||
|
|
||||||
|
es206_client = ElasticSearchClient(host='192.168.0.206')
|
||||||
|
|
||||||
|
# 2. 读取城市列表与清洗
|
||||||
|
city_df = pd.DataFrame(list(server_area_conn.find({}, {'city_grade': 1, 'display': 1})))
|
||||||
|
city_df = city_df.rename(columns={'city_grade': 'city_level', 'display': 'city'})
|
||||||
|
city_df = city_df[city_df['city_level'] != 0]
|
||||||
|
# 昆玉无小区
|
||||||
|
city_df = city_df[city_df['city'] != '昆玉'].reset_index(drop=True)
|
||||||
|
|
||||||
|
# 3. 巨量 MongoDB 查询与路径准备
|
||||||
|
seaweed_df = pd.DataFrame(
|
||||||
|
list(seaweed_conn.find({'cat': 'district', 'status': 0},
|
||||||
|
{'city': 1, 'region': 1, 'name': 1, 'alias': 1, 'addr_alias': 1})
|
||||||
|
.batch_size(100000)))
|
||||||
|
|
||||||
|
path = "/opt/airflow/dags/repo/dags/business/business/community/data"
|
||||||
|
|
||||||
|
aim_path = "/home/airflow/data/stat"
|
||||||
|
if not os.path.exists(aim_path):
|
||||||
|
os.makedirs(aim_path)
|
||||||
|
|
||||||
|
ret_df = pd.read_excel(path + '/财力评级分布情况20221215.xlsx')
|
||||||
|
|
||||||
|
# 4. 双层大循环处理小区与别名
|
||||||
|
for index, item in city_df.iterrows():
|
||||||
|
city = item['city']
|
||||||
|
region_df = seaweed_df[(seaweed_df['city'] == city)].copy()
|
||||||
|
alias_count = 0
|
||||||
|
addr_count = 0
|
||||||
|
seaweed_count = 0
|
||||||
|
# 楼盘数量
|
||||||
|
city_df.loc[index, 'community_count'] = len(region_df)
|
||||||
|
if len(region_df) == 0:
|
||||||
|
log.error(f"该城市{city}小区数量为0")
|
||||||
|
for index1, item1 in region_df.iterrows():
|
||||||
|
flag = True
|
||||||
|
if type(item1['alias']) == list:
|
||||||
|
if len(item1['alias']) > 0:
|
||||||
|
alias_count += len(item1['alias'])
|
||||||
|
seaweed_count += 1
|
||||||
|
flag = False
|
||||||
|
if type(item1['addr_alias']) == list:
|
||||||
|
if len(item1['addr_alias']) > 0:
|
||||||
|
addr_count += len(item1['addr_alias'])
|
||||||
|
if len(item1['addr_alias']) > 0 and flag is True:
|
||||||
|
seaweed_count += 1
|
||||||
|
# 楼盘别名总数
|
||||||
|
city_df.loc[index, 'alias_count'] = alias_count
|
||||||
|
# 地址别名数量
|
||||||
|
city_df.loc[index, 'addr_alias_count'] = addr_count
|
||||||
|
# 有别名小区量【存在楼盘别名或地址别名】
|
||||||
|
city_df.loc[index, 'exist_alias_community_count'] = seaweed_count
|
||||||
|
|
||||||
|
df = city_df.copy()
|
||||||
|
|
||||||
|
# 5. 主力属性的多项重度 MongoDB Aggregation 统计
|
||||||
|
# 主力户型
|
||||||
|
main_type_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
||||||
|
{'$match': {'cat': 'district', 'status': 0, 'main_type': {'$ne': None}}},
|
||||||
|
{'$group': {'_id': "$city", 'main_type_count': {'$sum': 1}}}])))
|
||||||
|
main_type_count = main_type_count.rename(columns={'_id': 'city'})
|
||||||
|
df = pd.merge(df, main_type_count, how='left', on=['city'])
|
||||||
|
df['main_type_coverage'] = df['main_type_count'] * 100 / df['community_count']
|
||||||
|
|
||||||
|
# 主力面积
|
||||||
|
main_type_area_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
||||||
|
{'$match': {'cat': 'district', 'status': 0, 'main_type_area': {'$ne': None}}},
|
||||||
|
{'$group': {'_id': "$city", 'main_type_area_count': {'$sum': 1}}}])))
|
||||||
|
main_type_area_count = main_type_area_count.rename(columns={'_id': 'city'})
|
||||||
|
df = pd.merge(df, main_type_area_count, how='left', on=['city'])
|
||||||
|
df['main_type_area_coverage'] = df['main_type_area_count'] * 100 / df['community_count']
|
||||||
|
|
||||||
|
# 物业类型
|
||||||
|
estate_type_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
||||||
|
{'$match': {'cat': 'district', 'status': 0, 'estate_type2': {'$ne': None}}},
|
||||||
|
{'$group': {'_id': "$city", 'estate_type_count': {'$sum': 1}}}])))
|
||||||
|
estate_type_count = estate_type_count.rename(columns={'_id': 'city'})
|
||||||
|
df = pd.merge(df, estate_type_count, how='left', on=['city'])
|
||||||
|
df['estate_type_coverage'] = df['estate_type_count'] * 100 / df['community_count']
|
||||||
|
|
||||||
|
# 建成年代
|
||||||
|
finish_building_date_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
||||||
|
{'$match': {'cat': 'district', 'status': 0, 'finish_building_date': {'$ne': None}}},
|
||||||
|
{'$group': {'_id': "$city", 'finish_building_date_count': {'$sum': 1}}}])))
|
||||||
|
finish_building_date_count = finish_building_date_count.rename(columns={'_id': 'city'})
|
||||||
|
df = pd.merge(df, finish_building_date_count, how='left', on=['city'])
|
||||||
|
df['finish_building_date_coverage'] = df['finish_building_date_count'] * 100 / df['community_count']
|
||||||
|
|
||||||
|
# 占地面积
|
||||||
|
all_area_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
||||||
|
{'$match': {'cat': 'district', 'status': 0, 'all_area': {'$ne': None}}},
|
||||||
|
{'$group': {'_id': "$city", 'all_area_count': {'$sum': 1}}}])))
|
||||||
|
all_area_count = all_area_count.rename(columns={'_id': 'city'})
|
||||||
|
df = pd.merge(df, all_area_count, how='left', on=['city'])
|
||||||
|
df['all_area_coverage'] = df['all_area_count'] * 100 / df['community_count']
|
||||||
|
|
||||||
|
# 建筑面积
|
||||||
|
build_area_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
||||||
|
{'$match': {'cat': 'district', 'status': 0, 'build_area': {'$ne': None}}},
|
||||||
|
{'$group': {'_id': "$city", 'build_area_count': {'$sum': 1}}}])))
|
||||||
|
build_area_count = build_area_count.rename(columns={'_id': 'city'})
|
||||||
|
df = pd.merge(df, build_area_count, how='left', on=['city'])
|
||||||
|
df['build_area_coverage'] = df['build_area_count'] * 100 / df['community_count']
|
||||||
|
|
||||||
|
# 绿化率
|
||||||
|
greening_rate_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
||||||
|
{'$match': {'cat': 'district', 'status': 0, 'virescence_percent': {'$ne': None}}},
|
||||||
|
{'$group': {'_id': "$city", 'greening_rate_count': {'$sum': 1}}}])))
|
||||||
|
greening_rate_count = greening_rate_count.rename(columns={'_id': 'city'})
|
||||||
|
df = pd.merge(df, greening_rate_count, how='left', on=['city'])
|
||||||
|
df['greening_rate_coverage'] = df['greening_rate_count'] * 100 / df['community_count']
|
||||||
|
|
||||||
|
# 容积率
|
||||||
|
volume_rate_count = pd.DataFrame(list(seaweed_conn.aggregate([
|
||||||
|
{'$match': {'cat': 'district', 'status': 0, 'cubage_percent': {'$ne': None}}},
|
||||||
|
{'$group': {'_id': "$city", 'volume_rate_count': {'$sum': 1}}}])))
|
||||||
|
volume_rate_count = volume_rate_count.rename(columns={'_id': 'city'})
|
||||||
|
df = pd.merge(df, volume_rate_count, how='left', on=['city'])
|
||||||
|
df['volume_rate_coverage'] = df['volume_rate_count'] * 100 / df['community_count']
|
||||||
|
|
||||||
|
# 6. 人均/财力等 Elasticsearch 批量循环查询
|
||||||
|
df['total_price_count'] = None
|
||||||
|
df['estate_charge_count'] = None
|
||||||
|
df['avg_cost_count'] = None
|
||||||
|
df['consumption_rating_count'] = None
|
||||||
|
for index, item in df.iterrows():
|
||||||
|
curr_city = item['city']
|
||||||
|
sql = f"select count(*) from community_summary where city='{curr_city}' and total_price>0 "
|
||||||
|
num = es206_client.search_by_sql(sql)['hits']['total']['value']
|
||||||
|
df.loc[index, 'total_price_count'] = num
|
||||||
|
|
||||||
|
sql = f"select count(*) from community_summary where city='{curr_city}' and estate_charge>0 "
|
||||||
|
estate_charge_num = es206_client.search_by_sql(sql)['hits']['total']['value']
|
||||||
|
df.loc[index, 'estate_charge_count'] = estate_charge_num
|
||||||
|
|
||||||
|
sql = f"select count(*) from community_summary where city='{curr_city}' and avg_cost>0 "
|
||||||
|
avg_cost_count = es206_client.search_by_sql(sql)['hits']['total']['value']
|
||||||
|
df.loc[index, 'avg_cost_count'] = avg_cost_count
|
||||||
|
|
||||||
|
sql = f"select count(*) from community_summary where city='{curr_city}' and consumption_rating>0 "
|
||||||
|
consumption_rating_num = es206_client.search_by_sql(sql)['hits']['total']['value']
|
||||||
|
df.loc[index, 'consumption_rating_count'] = consumption_rating_num
|
||||||
|
|
||||||
|
df['total_price_coverage'] = df['total_price_count'] * 100 / df['community_count']
|
||||||
|
df['consumption_rating_coverage'] = df['consumption_rating_count'] * 100 / df['community_count']
|
||||||
|
df['estate_charge_coverage'] = df['estate_charge_count'] * 100 / df['community_count']
|
||||||
|
df['avg_cost_coverage'] = df['avg_cost_count'] * 100 / df['community_count']
|
||||||
|
|
||||||
|
# 7. 近一年成交量 MongoDB 加载
|
||||||
|
actions = list()
|
||||||
|
for index, item in seaweed_df.iterrows():
|
||||||
|
if type(item['alias']) == list:
|
||||||
|
for name in item['alias']:
|
||||||
|
actions.append({'_id': item['_id'], 'city': item['city'], 'name': name, 'region': item['region']})
|
||||||
|
alias_df = pd.DataFrame(actions)
|
||||||
|
seaweed_alias_df = pd.concat([seaweed_df[['_id', 'city', 'region', 'name']], alias_df])
|
||||||
|
deal_price_df = pd.DataFrame(list(deal_price_conn.find(
|
||||||
|
{'trade_date': {'$gte': dateutils.add_months(dateutils.datetime.datetime.now(), days=-365)}},
|
||||||
|
{'city': 1, 'region': 1, 'district_name': 1, '_id': 0}).batch_size(10000)))
|
||||||
|
deal_price_df = deal_price_df.rename(columns={'district_name': 'name'})
|
||||||
|
deal_price_seaweed_df = pd.merge(deal_price_df, seaweed_alias_df, how='left', on=['city', 'region', 'name'])
|
||||||
|
# 剔除没有配到的小区
|
||||||
|
deal_price_seaweed_notnull_df = deal_price_seaweed_df.dropna(subset=['_id'])
|
||||||
|
deal_price_seaweed_notnull_df.loc[:, 'one_year_deal'] = deal_price_seaweed_notnull_df.groupby(['city'])[
|
||||||
|
'city'].transform('size')
|
||||||
|
deal_price_half_year_df = deal_price_seaweed_notnull_df[['city', 'one_year_deal']].drop_duplicates(keep='first')
|
||||||
|
df = pd.merge(df, deal_price_half_year_df, how='left', on=['city'])
|
||||||
|
|
||||||
|
# 8. 均价租金统计
|
||||||
|
avg_price_df = commutils.get_avg_price()
|
||||||
|
rent_price_df = commutils.get_rent_price()
|
||||||
|
|
||||||
|
avg_price_df['avg_price_count'] = avg_price_df.groupby(by=['city'])['_id'].transform('count')
|
||||||
|
rent_price_df['sqmetre_rent_count'] = rent_price_df.groupby(by=['city'])['_id'].transform('count')
|
||||||
|
|
||||||
|
avg_price_df = avg_price_df[['city', 'avg_price_count']].drop_duplicates(keep='first')
|
||||||
|
rent_price_df = rent_price_df[['city', 'sqmetre_rent_count']].drop_duplicates(keep='first')
|
||||||
|
|
||||||
|
df = pd.merge(df, avg_price_df, how='left', on=['city'])
|
||||||
|
df = pd.merge(df, rent_price_df, how='left', on=['city'])
|
||||||
|
|
||||||
|
df['avg_price_coverage'] = df['avg_price_count'] * 100 / df['community_count']
|
||||||
|
df['sqmetre_rent_coverage'] = df['sqmetre_rent_count'] * 100 / df['community_count']
|
||||||
|
|
||||||
|
df.fillna(0, inplace=True)
|
||||||
|
|
||||||
|
df['community_count'] = df['community_count'].astype(int)
|
||||||
|
df['avg_price_count'] = df['avg_price_count'].astype(int)
|
||||||
|
df['sqmetre_rent_count'] = df['sqmetre_rent_count'].astype(int)
|
||||||
|
df['one_year_deal'] = df['one_year_deal'].astype(int)
|
||||||
|
df['alias_count'] = df['alias_count'].astype(int)
|
||||||
|
df['addr_alias_count'] = df['addr_alias_count'].astype(int)
|
||||||
|
df['exist_alias_community_count'] = df['exist_alias_community_count'].astype(int)
|
||||||
|
|
||||||
|
df = df.round({'avg_price_coverage': 2, 'sqmetre_rent_coverage': 2, 'main_type_coverage': 2, 'main_type_area_coverage': 2, 'total_price_coverage': 2, 'estate_type_coverage': 2,
|
||||||
|
'finish_building_date_coverage': 2, 'all_area_coverage': 2, 'build_area_coverage': 2, 'estate_charge_coverage': 2, 'avg_cost_coverage': 2, 'consumption_rating_coverage': 2, 'greening_rate_coverage': 2, 'volume_rate_coverage': 2})
|
||||||
|
df = df[['city', 'community_count', 'city_level', 'avg_price_coverage', 'sqmetre_rent_coverage', 'alias_count', 'addr_alias_count',
|
||||||
|
'exist_alias_community_count', 'one_year_deal', 'main_type_coverage', 'main_type_area_coverage', 'total_price_coverage', 'estate_type_coverage',
|
||||||
|
'finish_building_date_coverage', 'all_area_coverage', 'build_area_coverage', 'estate_charge_coverage', 'avg_cost_coverage', 'consumption_rating_coverage', 'greening_rate_coverage', 'volume_rate_coverage']]
|
||||||
|
|
||||||
|
# 9. ClickHouse 写入与去重操作
|
||||||
|
df['weekend'] = dateutils.datetime.datetime.now()
|
||||||
|
clickHouseClient.execute(
|
||||||
|
"ALTER TABLE fangjia_stat.community_coverage_stat DELETE WHERE weekend = toDate('" + dateutils.format_date(dateutils.datetime.datetime.now(), '%Y-%m-%d') + "')")
|
||||||
|
clickHouseClient.to_sql(df, table='community_coverage_stat', if_exists='insert', order_by='weekend')
|
||||||
|
|
||||||
|
# 10. 文件输出与 NextCloud 上传
|
||||||
|
ret_df = pd.merge(ret_df, df, how='left', on=['city'])
|
||||||
|
del ret_df['是否合理']
|
||||||
|
ret_df = ret_df.rename(columns={'city': '城市', 'city_level': '城市级别', 'community_count': "楼盘数量", "alias_count": "别名数量", "addr_alias_count": "地址别名数量", "exist_alias_community_count": "有别名覆盖小区数量",
|
||||||
|
'estate_type_coverage': '物业类型覆盖率', 'avg_price_coverage': '均价覆盖率', 'sqmetre_rent_coverage': '平米租金覆盖率', 'total_price_coverage': '户均总价覆盖率', 'estate_charge_coverage': '物业费覆盖率', 'avg_cost_coverage': '人均消费覆盖率', 'main_type_coverage': '主力户型覆盖率', 'main_type_area_coverage': '主力面积覆盖率', 'finish_building_date_coverage': '建成年代覆盖率', 'all_area_coverage': '占地面积覆盖率', 'build_area_coverage': '建筑面积覆盖率', 'consumption_rating_coverage': '财力评级覆盖率', 'greening_rate_coverage': '绿化率覆盖率', 'volume_rate_coverage': '容积率覆盖率'})
|
||||||
|
output_date = dateutils.format_date(dateutils.datetime.datetime.now())
|
||||||
|
aim_file_name = aim_path + "/" + output_date + '覆盖率统计.xlsx'
|
||||||
|
ret_df.to_excel(aim_file_name, index=False)
|
||||||
|
|
||||||
|
up_to_nextcloud()
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""
|
||||||
|
小区周边1公里交通地铁入库业务逻辑
|
||||||
|
"""
|
||||||
|
import datetime
|
||||||
|
import logging
|
||||||
|
import pandas as pd
|
||||||
|
import sys # 新增导入系统模块用于安全退出
|
||||||
|
from goojia_utils import MAIN_MONGO_CLIENT
|
||||||
|
from goojia_utils import dateutils
|
||||||
|
from sklearn.mixture import GaussianMixture
|
||||||
|
from pymongo import InsertOne, DeleteMany, ReplaceOne, UpdateOne
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
# ================== 🛡️ 安全运行入口 ==================
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
district_stat_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'district_stat')
|
||||||
|
district_analy_data_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'district_analy_data')
|
||||||
|
server_area_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'server_area')
|
||||||
|
|
||||||
|
# 1. 延迟进行重度 MongoDB 查询
|
||||||
|
weekend_list = list(district_stat_conn.find().sort([("weekend", -1)]).limit(1))
|
||||||
|
if not weekend_list:
|
||||||
|
logger.error("在 district_stat 集合中未找到有效的 weekend 记录,程序退出。")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
weekend = weekend_list[0]['weekend']
|
||||||
|
level_map = {"1": "S", "2": "A", "3": "B", "4": "C", "5": "D"}
|
||||||
|
|
||||||
|
logger.info(f"开始计算楼盘评级 weekend:{dateutils.format_date(weekend, '%Y-%m-%d')}")
|
||||||
|
|
||||||
|
# 2. 遍历各城市开展机器学习模型评级
|
||||||
|
for server_area in server_area_conn.find({'display': {'$ne': '全国'}}, {"display": 1}):
|
||||||
|
city = server_area["display"]
|
||||||
|
data = pd.DataFrame(
|
||||||
|
district_stat_conn.find({"city": city, "weekend": weekend},
|
||||||
|
{"_id": 0, "region": 1, "district_name": 1, "avg_price": 1}))
|
||||||
|
if "avg_price" not in data or len(data['avg_price'].unique()) < 5:
|
||||||
|
continue
|
||||||
|
data['city'] = city
|
||||||
|
logger.info(f"开始计算{city}楼盘评级 weekend:{dateutils.format_date(weekend, '%Y-%m-%d')}")
|
||||||
|
|
||||||
|
# 高斯混合模型训练及评估(延迟到真正执行时运行,避免污染解析阶段)
|
||||||
|
gmm = GaussianMixture(n_components=5, covariance_type='tied', max_iter=200, n_init=10).fit(
|
||||||
|
data[["avg_price"]])
|
||||||
|
data.loc[:, 'cluster'] = gmm.predict(data[["avg_price"]])
|
||||||
|
data.loc[:, 'price_mean_cluster'] = data.groupby('cluster')["avg_price"].transform('mean')
|
||||||
|
data.loc[:, "target"] = data['price_mean_cluster'].rank(method='dense', ascending=False).astype(int)
|
||||||
|
data = data.drop(columns=['cluster', 'price_mean_cluster'], axis=1)
|
||||||
|
data["community_rating"] = data['target'].apply(lambda x: level_map[str(x)])
|
||||||
|
|
||||||
|
opts = []
|
||||||
|
for item in data.to_dict('records'):
|
||||||
|
opts.append(UpdateOne({"city": city, "region": item["region"], "district_name": item["district_name"]},
|
||||||
|
{"$set": {"community_rating": item["community_rating"]}}, upsert=True
|
||||||
|
))
|
||||||
|
|
||||||
|
# 按照每 1000 条分割 updates 列表并执行 Bulk Write
|
||||||
|
batch_size = 1000
|
||||||
|
batches = [opts[i:i + batch_size] for i in range(0, len(opts), batch_size)]
|
||||||
|
|
||||||
|
cnt = 0
|
||||||
|
for batch in batches:
|
||||||
|
cnt = cnt + 1
|
||||||
|
logger.info(f"{city}楼盘评级更新数据库, 进度:{cnt}/{len(batches)}")
|
||||||
|
result = district_analy_data_conn.bulk_write(batch)
|
||||||
|
print(f"当前批次更新的文档数量: {result.modified_count}")
|
||||||
|
|
||||||
|
logger.info(f"楼盘评级计算结束{dateutils.format_date(datetime.datetime.utcnow(), '%Y-%m-%d')}")
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
|
|
||||||
with DAG(
|
with DAG(
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
|
|
||||||
with DAG(
|
with DAG(
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
from airflow.operators.bash import BashOperator
|
from airflow.providers.standard.operators.bash import BashOperator
|
||||||
import pendulum
|
import pendulum
|
||||||
from airflow import DAG
|
from airflow import DAG
|
||||||
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# from airflow.providers.standard.operators.bash import BashOperator
|
||||||
|
# import pendulum
|
||||||
|
# from airflow import DAG
|
||||||
|
#
|
||||||
|
# with DAG(
|
||||||
|
# dag_id="increase_decrease_city_region_dag",
|
||||||
|
# # 每月的最后一天运行
|
||||||
|
# schedule="0 10 L * *",
|
||||||
|
# start_date=pendulum.datetime(2024, 5, 30, tz="Asia/Shanghai"),
|
||||||
|
# description="城市区域涨跌幅数据统计",
|
||||||
|
# catchup=True
|
||||||
|
# ) as dag:
|
||||||
|
# t1 = BashOperator(
|
||||||
|
# task_id='increase_decrease_city_region',
|
||||||
|
# bash_command='python /opt/airflow/dags/repo/dags/stat/cityPrice/increase_decrease_city_region.py',
|
||||||
|
# )
|
||||||
|
# t1
|
||||||
+42
-27
@@ -10,34 +10,8 @@ import sys
|
|||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
city_num = sys.argv[1] if len(sys.argv) > 1 else None
|
|
||||||
if city_num is not None:
|
|
||||||
log.info("输出参数" + city_num)
|
|
||||||
|
|
||||||
df = pd.DataFrame()
|
|
||||||
if city_num is not None and int(city_num) == 92:
|
|
||||||
df = pd.read_excel('/opt/airflow/dags/repo/dags/stat/evaluate/data/估值92城市数据统计.xlsx')
|
|
||||||
else:
|
|
||||||
df = pd.read_excel('/opt/airflow/dags/repo/dags/stat/evaluate/data/估值数据统计.xlsx')
|
|
||||||
year_month_day = dateutils.format_date(datetime.datetime.now())
|
|
||||||
path = "/home/airflow/data/evaluate"
|
|
||||||
aim_file_name = path + '/估值数据统计结果' + year_month_day + '.xlsx'
|
|
||||||
if not os.path.exists(path):
|
|
||||||
os.makedirs(path)
|
|
||||||
|
|
||||||
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.206')
|
|
||||||
district_stat_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'district_stat') # 成交
|
|
||||||
average_statistics_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'average_statistics') # 第三方均价
|
|
||||||
deal_price_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'deal_price')
|
|
||||||
|
|
||||||
seaweed_df = pd.DataFrame(
|
|
||||||
list(seaweed_conn.find({'cat': 'district', 'status': 0}, {'city': 1, 'region': 1, 'name': 1, 'mapping_alias': 1})
|
|
||||||
.batch_size(10000)))
|
|
||||||
seaweed_df = seaweed_df.rename(columns={'mapping_alias': 'alias'})
|
|
||||||
|
|
||||||
cities = df[['城市']].drop_duplicates(keep='first')['城市'].values.tolist()
|
|
||||||
|
|
||||||
|
# ================== 核心统计函数(在全局定义,供 main 调用) ==================
|
||||||
|
|
||||||
def count_stat():
|
def count_stat():
|
||||||
"""
|
"""
|
||||||
@@ -128,7 +102,48 @@ def deal_stat():
|
|||||||
new_df = pd.merge(new_df, seaweed_half_year_rename_df, how='left', on=['城市'])
|
new_df = pd.merge(new_df, seaweed_half_year_rename_df, how='left', on=['城市'])
|
||||||
new_df.to_excel(aim_file_name, index=False)
|
new_df.to_excel(aim_file_name, index=False)
|
||||||
|
|
||||||
|
# ================== 🛡️ 安全运行入口 ==================
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# 1. 只有以脚本形式运行时,才解析命令行参数
|
||||||
|
city_num = sys.argv[1] if len(sys.argv) > 1 else None
|
||||||
|
if city_num is not None:
|
||||||
|
log.info("输出参数" + city_num)
|
||||||
|
|
||||||
|
# 2. 读取 Excel 配置
|
||||||
|
df = pd.DataFrame()
|
||||||
|
# 增加额外的 try-except 容错,防止意外传入非数字字符串(比如在别处不小心执行时)
|
||||||
|
try:
|
||||||
|
if city_num is not None and int(city_num) == 92:
|
||||||
|
df = pd.read_excel('/opt/airflow/dags/repo/dags/stat/evaluate/data/估值92城市数据统计.xlsx')
|
||||||
|
else:
|
||||||
|
df = pd.read_excel('/opt/airflow/dags/repo/dags/stat/evaluate/data/估值数据统计.xlsx')
|
||||||
|
except ValueError:
|
||||||
|
log.warning(f"无法将参数 '{city_num}' 转换为整数,将使用默认数据源进行统计。")
|
||||||
|
df = pd.read_excel('/opt/airflow/dags/repo/dags/stat/evaluate/data/估值数据统计.xlsx')
|
||||||
|
|
||||||
|
year_month_day = dateutils.format_date(datetime.datetime.now())
|
||||||
|
path = "/home/airflow/data/evaluate"
|
||||||
|
aim_file_name = path + '/估值数据统计结果' + year_month_day + '.xlsx'
|
||||||
|
if not os.path.exists(path):
|
||||||
|
os.makedirs(path)
|
||||||
|
|
||||||
|
# 3. 延迟初始化数据库连接(避免在 Airflow 解析阶段浪费连接资源)
|
||||||
|
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
||||||
|
es206_client = ElasticSearchClient(host='192.168.0.206')
|
||||||
|
district_stat_conn = MAIN_MONGO_CLIENT.get_collection('fangjia_stat', 'district_stat') # 成交
|
||||||
|
average_statistics_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'average_statistics') # 第三方均价
|
||||||
|
deal_price_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'deal_price')
|
||||||
|
|
||||||
|
# 4. 加载 MongoDB 数据
|
||||||
|
seaweed_df = pd.DataFrame(
|
||||||
|
list(seaweed_conn.find({'cat': 'district', 'status': 0}, {'city': 1, 'region': 1, 'name': 1, 'mapping_alias': 1})
|
||||||
|
.batch_size(10000)))
|
||||||
|
seaweed_df = seaweed_df.rename(columns={'mapping_alias': 'alias'})
|
||||||
|
|
||||||
|
cities = df[['城市']].drop_duplicates(keep='first')['城市'].values.tolist()
|
||||||
|
|
||||||
|
# 5. 执行主统计逻辑
|
||||||
log.info("开始统计小区数量、近半年第三方均价、近半年成交信息")
|
log.info("开始统计小区数量、近半年第三方均价、近半年成交信息")
|
||||||
count_stat()
|
count_stat()
|
||||||
# third_avg_stat()
|
# third_avg_stat()
|
||||||
+31
-14
@@ -8,22 +8,9 @@ import datetime
|
|||||||
import sys
|
import sys
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
sell_num = sys.argv[1] if len(sys.argv) > 1 else "2"
|
|
||||||
sell_num = int(sell_num)
|
|
||||||
log.info("输出参数" + str(sell_num))
|
|
||||||
|
|
||||||
year_month_day = dateutils.format_date(datetime.datetime.now())
|
|
||||||
aim_file_name = '/home/airflow/data/evaluate/估值数据统计结果' + year_month_day + '.xlsx'
|
|
||||||
start_time = dateutils.format_date(dateutils.add_months(dateutils.datetime.datetime.now(), days=-93))
|
|
||||||
one_year_time = dateutils.format_date(dateutils.add_months(dateutils.datetime.datetime.now(), days=-366))
|
|
||||||
|
|
||||||
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
|
||||||
es206_client = ElasticSearchClient(host='192.168.0.206')
|
|
||||||
|
|
||||||
seaweed_df = pd.DataFrame(list(seaweed_conn.find({'cat': 'district', 'status': 0}, {'city': 1, 'region': 1, 'name': 1, 'mapping_alias': 1})
|
|
||||||
.batch_size(10000)))
|
|
||||||
seaweed_df = seaweed_df.rename(columns={'mapping_alias': 'alias'})
|
|
||||||
|
|
||||||
|
# ================== 核心函数定义(供 main 调用) ==================
|
||||||
|
|
||||||
def get_sell(df, daysBefore=365):
|
def get_sell(df, daysBefore=365):
|
||||||
cities = df[['城市']].drop_duplicates(keep='first')['城市'].values.tolist()
|
cities = df[['城市']].drop_duplicates(keep='first')['城市'].values.tolist()
|
||||||
@@ -115,6 +102,7 @@ def merge_aim():
|
|||||||
df = pd.merge(df, need_df, how='left', on=['城市'])
|
df = pd.merge(df, need_df, how='left', on=['城市'])
|
||||||
df.to_excel(aim_file_name, index=False)
|
df.to_excel(aim_file_name, index=False)
|
||||||
|
|
||||||
|
|
||||||
def up_to_nextcloud():
|
def up_to_nextcloud():
|
||||||
"""
|
"""
|
||||||
上传统计信息至nextcloud
|
上传统计信息至nextcloud
|
||||||
@@ -127,6 +115,35 @@ def up_to_nextcloud():
|
|||||||
nxc = NextCloud(endpoint=NEXTCLOUD_URL, user=NEXTCLOUD_USERNAME, password=NEXTCLOUD_PASSWORD, json_output=True)
|
nxc = NextCloud(endpoint=NEXTCLOUD_URL, user=NEXTCLOUD_USERNAME, password=NEXTCLOUD_PASSWORD, json_output=True)
|
||||||
nxc.upload_file(aim_file_name, aim_file_path)
|
nxc.upload_file(aim_file_name, aim_file_path)
|
||||||
|
|
||||||
|
|
||||||
|
# ================== 🛡️ 安全运行入口 ==================
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# 1. 只有脚本运行时,才解析命令行参数并转为整数
|
||||||
|
sell_num_arg = sys.argv[1] if len(sys.argv) > 1 else "2"
|
||||||
|
try:
|
||||||
|
sell_num = int(sell_num_arg)
|
||||||
|
except ValueError:
|
||||||
|
log.warning(f"无法将参数 '{sell_num_arg}' 转换为整数,将使用默认值 2。")
|
||||||
|
sell_num = 2
|
||||||
|
log.info("输出参数" + str(sell_num))
|
||||||
|
|
||||||
|
# 2. 统计时间范围及存储文件名定义
|
||||||
|
year_month_day = dateutils.format_date(datetime.datetime.now())
|
||||||
|
aim_file_name = '/home/airflow/data/evaluate/估值数据统计结果' + year_month_day + '.xlsx'
|
||||||
|
start_time = dateutils.format_date(dateutils.add_months(dateutils.datetime.datetime.now(), days=-93))
|
||||||
|
one_year_time = dateutils.format_date(dateutils.add_months(dateutils.datetime.datetime.now(), days=-366))
|
||||||
|
|
||||||
|
# 3. 延迟数据库初始化(避开 Airflow 解析器扫描)
|
||||||
|
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
||||||
|
es206_client = ElasticSearchClient(host='192.168.0.206')
|
||||||
|
|
||||||
|
# 4. 加载基础数据
|
||||||
|
seaweed_df = pd.DataFrame(list(seaweed_conn.find({'cat': 'district', 'status': 0}, {'city': 1, 'region': 1, 'name': 1, 'mapping_alias': 1})
|
||||||
|
.batch_size(10000)))
|
||||||
|
seaweed_df = seaweed_df.rename(columns={'mapping_alias': 'alias'})
|
||||||
|
|
||||||
|
# 5. 开始核心统计与上传逻辑
|
||||||
log.info("开始统计统计近三个月、近一年样本量及小区属性")
|
log.info("开始统计统计近三个月、近一年样本量及小区属性")
|
||||||
sell_stat()
|
sell_stat()
|
||||||
property_stat()
|
property_stat()
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
from airflow import DAG
|
|
||||||
from airflow.operators.python_operator import PythonOperator
|
|
||||||
from datetime import datetime
|
|
||||||
from goojia_utils import dingutils
|
|
||||||
|
|
||||||
# def send_dingding_alert(context):
|
|
||||||
# print('监测到错误')
|
|
||||||
# task_instance = context.get('task_instance')
|
|
||||||
# url = task_instance.log_url.replace("http://localhost:8080", "https://airflow.fangjia.com")
|
|
||||||
# message = f"【airflow】 任务{task_instance.task_id}错误,请点击{url}查看!"
|
|
||||||
# print(message)
|
|
||||||
# dingutils.send_text(message, "ae14f50045e9375c354940a2afb86f14e453bd1f08f78da0ba6e788d35bccec4")
|
|
||||||
# print("success")
|
|
||||||
#
|
|
||||||
def fail_task():
|
|
||||||
raise ValueError("This task is designed to fail")
|
|
||||||
#
|
|
||||||
# default_args = {
|
|
||||||
# "owner": "airflow",
|
|
||||||
# "retries": 0,
|
|
||||||
# "on_failure_callback": send_dingding_alert, # 任务失败时触发钉钉告警
|
|
||||||
# }
|
|
||||||
|
|
||||||
|
|
||||||
dag = DAG(
|
|
||||||
'test_failure_notification',
|
|
||||||
#default_args=default_args,
|
|
||||||
start_date=datetime(2025, 4, 22),
|
|
||||||
schedule=None
|
|
||||||
)
|
|
||||||
|
|
||||||
task = PythonOperator(
|
|
||||||
task_id='failing_task',
|
|
||||||
python_callable=fail_task,
|
|
||||||
dag=dag
|
|
||||||
)
|
|
||||||
Reference in New Issue
Block a user