diff --git a/dags/office/sell/base_price.py b/dags/office/sell/base_price.py index cb9ee11..3638514 100644 --- a/dags/office/sell/base_price.py +++ b/dags/office/sell/base_price.py @@ -128,6 +128,64 @@ def calcByOffice(city, district, office_name): upsert=True) 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 calcByCity(city, year_month): """