feat: 在 base_price.py 的单写字楼重算路径中追加自动计算 mom/yoy 环比同比指标的后置处理,避免重算后指标丢失

This commit is contained in:
王文艳
2026-08-17 12:56:46 +08:00
parent 3bdbc5ca8c
commit c4556a9271
+58
View File
@@ -127,6 +127,64 @@ def calcByOffice(city, district, office_name):
upsert=True)
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 calcByCity(city, year_month):
"""