feat(office): auto-calculate mom and yoy for city, district, and office monthly stats

This commit is contained in:
王文艳
2026-10-19 11:54:35 +08:00
parent 0d65af4be7
commit 2d266a30c2
6 changed files with 206 additions and 33 deletions
+44
View File
@@ -187,6 +187,49 @@ def calculate_mom_yoy_for_office(city, district, office_name):
office_sell_stat_conn.bulk_write(actions)
def calculate_mom_yoy_by_month(year_month, city=None):
"""
批量计算某月所有写字楼出售的 mom (环比) 和 yoy (同比) 并更新
"""
curr_date = int(year_month)
year = curr_date // 100
month = curr_date % 100
prev_date = (year - 1) * 100 + 12 if month == 1 else curr_date - 1
ly_date = curr_date - 100
base_query = {'cat': 'office'}
if pd.notna(city) and city != '':
base_query['city'] = city
proj = {'_id': 1, 'city': 1, 'district': 1, 'name': 1, 'avg_price': 1}
curr_docs = list(office_sell_stat_conn.find({**base_query, 'date': curr_date}, proj))
if not curr_docs:
return
prev_docs = list(office_sell_stat_conn.find({**base_query, 'date': prev_date}, proj))
ly_docs = list(office_sell_stat_conn.find({**base_query, 'date': ly_date}, proj))
prev_map = {(d.get('city'), d.get('district'), d.get('name')): d.get('avg_price') for d in prev_docs if d.get('avg_price')}
ly_map = {(d.get('city'), d.get('district'), d.get('name')): d.get('avg_price') for d in ly_docs if d.get('avg_price')}
actions = []
for doc in curr_docs:
curr_price = doc.get('avg_price')
if not curr_price:
continue
key = (doc.get('city'), doc.get('district'), doc.get('name'))
prev_price = prev_map.get(key)
ly_price = ly_map.get(key)
mom = round((curr_price - prev_price) / prev_price * 100, 2) if prev_price else None
yoy = round((curr_price - ly_price) / ly_price * 100, 2) if ly_price else None
actions.append(UpdateOne({'_id': doc['_id']}, {'$set': {'mom': mom, 'yoy': yoy}}))
if len(actions) == 5000:
office_sell_stat_conn.bulk_write(actions)
actions.clear()
if actions:
office_sell_stat_conn.bulk_write(actions)
def calcByCity(city, year_month):
"""
写字楼基准价
@@ -214,6 +257,7 @@ def calcByCity(city, year_month):
office = getOffice(city)
update_office(city, office, sample, year_month)
calculate_mom_yoy_by_month(year_month, city)
def update_office(city, office, sample, year_month):