第三方均价输出

This commit is contained in:
muliangshu
2024-07-22 17:13:48 +08:00
parent 5d8397ec85
commit 3cda5cd211
6 changed files with 406 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
from pymongo import MongoClient
def getMongo(*args):
if len(args) == 6:
con = MongoClient(args[0], args[1]) # 获取链接\
db_auth = con.fangjia_craw
if args[2] =="vip_site":
db_auth.authenticate(args[4], args[5],"fangjia_craw")
else:
db_auth.authenticate(args[4], args[5],"admin")
db = con[args[2]] # 关联数据库
collection = db[args[3]] # 关联数据表
elif len(args) == 4:
con = MongoClient(args[0], args[1]) # 获取链接
db = con[args[2]] # 关联数据库
collection = db[args[3]] # 关联数据表
return collection
#线上小区库
seaweed_on = getMongo("192.168.0.43",28017,"fangjia","seaweed","developer","G00IDCDEV12385")
sz_price_on = getMongo("192.168.0.43",28017,"fangjia","sz_price","developer","G00IDCDEV12385")
district_stat_on = getMongo("192.168.0.43",28017,"fangjia_stat","district_stat","developer","G00IDCDEV12385")
seaweed_map = getMongo("192.168.0.235",27018,"fangjia","seaweedmap")
web_community_check = getMongo("192.168.0.235",27018,"fangjia","web_community_check")
web_invalid_comm = getMongo("192.168.0.235",27018,"fangjia","web_invalid_comm")
addr_nine_level = getMongo("192.168.0.206",27020,"etl","nine_level")
gxd_price = getMongo("192.168.0.43",28017,"fangjia","confirm_price_data","developer","G00IDCDEV12385")
+81
View File
@@ -0,0 +1,81 @@
from mongo_client import seaweed_on,seaweed_map,addr_nine_level,district_stat_on,gxd_price
import pandas as pd
import datetime
import pytz
pd.set_option ('display.max_colwidth',5)
def parse_date(time, fm='%Y-%m-%d'):
pacific = pytz.timezone('Asia/Shanghai')
return pacific.localize(datetime.datetime.strptime(time, fm))
def get_last_weekend():
sunday = datetime.datetime.utcnow()
sunday = sunday.replace(hour=0, minute=0, second=0, microsecond=0)
one_day = datetime.timedelta(days=1)
while sunday.weekday() != 6:
sunday -= one_day
pacific = pytz.timezone('Asia/Shanghai')
return pacific.localize(sunday)
confirm_date = parse_date("2024-05-20")
def get_seaweed(city=None,status=0):
seaweed_fields = {"city": 1, "region": 1, "name": 1,'estate_type2':1,'cat':1,"address":1,"alias":1,"lat":1,"lng":1,"addr_alias":1,"quality":1,"name_cat":1,"mapping_alias":1,"m_date":1,"is_new":1}
# seaweed_fields = {"_id": 0}
if city:
if city in ['阿坝','玉树','甘孜','德宏','迪庆','海北','海西','黄南','海南','怒江','文山','西双版纳','凉山','果洛']:
city = city+'州'
elif city in ['锡林郭勒','兴安','阿拉善']:
city = city+'盟'
elif city=='克州':
city = '克孜勒苏'
elif city=='博州':
city = '博尔塔拉'
elif city=='巴州':
city = '巴音郭楞'
seaweed_condition = {"cat": "district", "status": status, 'city':city}
else:
seaweed_condition = {"cat": "district", "status": status}
seaweed_data = seaweed_on.find(seaweed_condition, seaweed_fields)
seaweed_df = pd.DataFrame(seaweed_data)
seaweed_df = seaweed_df.rename(columns={'estate_type2': 'property_type'})
return seaweed_df
def get_map(city=None):
# seaweed_fields = {"city": 1, "region": 1, "name": 1,"address":1,"alias":1,"lat":1,"lng":1,"estate_type2":1,"addr_alias":1}
seaweed_fields = {"_id": 0}
if city:
seaweed_condition = {'city':city}
else:
seaweed_condition = {}
seaweed_map_data = seaweed_map.find(seaweed_condition, seaweed_fields)
seaweed_map_df = pd.DataFrame(seaweed_map_data)
return seaweed_map_df
def get_addr_nine_level(count):
_fields = {"address":1,"province":1,"city": 1, "district": 1,"township": 1, "name": 1,"":1}
_condition = {'address':{"$exists": True, "$ne": None},"remark":{"$exists": False}}
addr_nine_data = addr_nine_level.find(_condition,_fields).limit(count)
addr_nine_df = pd.DataFrame(addr_nine_data)
return addr_nine_df
def get_district_stat_on(city=None):
price_date = get_last_weekend()
stat_fields = {"_id": 0, "city": 1, "region": 1, "district_name": 1, "avg_price": 1,"avg_price_2b":1}
if city:
stat_condition = {'city':city,"weekend": price_date}
else:
stat_condition = {"weekend": price_date}
stat_data = district_stat_on.find(stat_condition, stat_fields)
stat_df = pd.DataFrame(stat_data)
stat_df = stat_df.rename(columns={'district_name': 'name'})
return stat_df
def get_gxd_price():
gxd_fields = {"_id": 0}
gxd_condition = {'source':'GXD'}
gxd_price_data = gxd_price.find(gxd_condition, gxd_fields)
gxd_price_df = pd.DataFrame(gxd_price_data)
return gxd_price_df
if __name__ == '__main__':
city = '厦门'
df = get_gxd_price()
print(df.head())
+42
View File
@@ -0,0 +1,42 @@
import os
import pandas as pd
from pandas import DataFrame
from retrying import retry
from sqlalchemy import create_engine
# os.environ["NLS_LANG"] = "AMERICAN_AMERICA.AL32UTF8"
class PgsqlDb:
"""
PgsqlDb Database Base Class
"""
def __init__(self,db):
if db == 'warehouse':
url=f"postgresql+psycopg2://postgres:postgres@192.168.0.236:5432/{db}"
elif db == 'fangjia':
url = f"postgresql+psycopg2://postgres:Goojia123456@192.168.0.235:5432/{db}"
self.engine = create_engine(url, echo=False,client_encoding='utf-8')
@retry(stop_max_attempt_number=3, wait_random_min=1000, wait_random_max=3000)
def read(self, sql) -> DataFrame:
"""
读取数据
:param sql:
:return:
"""
data_df = pd.read_sql(sql, con=self.engine)
return data_df
@retry(stop_max_attempt_number=3, wait_random_min=1000, wait_random_max=3000)
def count(self, sql) -> int:
"""
执行统计类SQL
:param sql: eg:select count(1) from t
:return:
"""
return pd.read_sql_query(sql, con=self.engine).iat[0, 0]
def sql_execute(self,sql):
self.engine.execute(sql)
if __name__ == '__main__':
pgdb = PgsqlDb()
+100
View File
@@ -0,0 +1,100 @@
import pandas as pd
import os
from pgsql_client import PgsqlDb
os.environ['NLS_LANG'] = 'SAMPLIFIED CHINESE_CHINA.UTF8'
pgdb = PgsqlDb('warehouse')
pgdb_new = PgsqlDb('fangjia')
def get_community_base_price(cityid,yearmonth):
"""
查询提供建行小区数据
:param cr:
:return:
"""
sql = f"select gujia_admndiv_nm,gujia_bds_id,urbn_nm,comm_nm,gujiabds_clc_yrmo_val,gujia_comm_basic_prc,gujia_bds_clmtd from t_app_p9pha_plda.avm_community_base_price_gj_h where urbn_id='{cityid}' and gujiabds_clc_yrmo_val={yearmonth}"
data_df = pgdb.read(sql)
data_df = data_df.rename(columns={'gujia_admndiv_nm':'district','gujia_bds_id': '_id','urbn_nm':'city','comm_nm':'name','gujiabds_clc_yrmo_val':'yearmonth','gujia_comm_basic_prc':'price','gujia_bds_clmtd':'type'})
return data_df
def get_community_base_price_new(cityid,yearmonth):
"""
查询提供建行小区数据
:param cr:
:return:
"""
sql = f"select gujia_bds_id,urbn_nm,comm_nm,gujiabds_clc_yrmo_val,gujia_comm_basic_prc,gujia_bds_clmtd from price_stat.avm_community_base_price where urbn_id='{cityid}' and gujiabds_clc_yrmo_val={yearmonth}"
data_df = pgdb_new.read(sql)
data_df = data_df.rename(columns={'gujia_bds_id': '_id','urbn_nm':'city_copy','comm_nm':'name_copy','gujiabds_clc_yrmo_val':'yearmonth','gujia_comm_basic_prc':'price_new','gujia_bds_clmtd':'type_new'})
return data_df
def get_district_polyline(cityid=None,cr=None):
"""
查询提供建行小区数据
:param cr:
:return:
"""
if cityid:
sql = f"select * from bigdata_district_polyline_gd where cityid='{cityid}'"
else:
sql = f"select distinct city,distname from bigdata_district_polyline_gd"
queryse = cr.execute(sql)
columns = [i[0].lower() for i in queryse.description]
rs = cr.fetchall()
data_df = pd.DataFrame(rs,columns=columns)
return data_df
def get_community_ccb(cityid):
sql = f"select gujia_comm_id,gujia_admndiv_nm,comm_nm from base.t0831_bigdata_community_gj_h where urbn_id='{cityid}' and gujia_bds_bds_st=0"
data_df = pgdb.read(sql)
data_df = data_df.rename(columns={'gujia_comm_id': '_id','gujia_admndiv_nm':'region','comm_nm':'name'})
return data_df
def get_bak_community(cityid,cr):
"""
查询小区数据
:param cr:
:return:
"""
sql = f"select a.*,b.longitude,b.latitude,c.distname from bigdata_community_bak a left join (select cityid, objectid, LONGITUDE, LATITUDE from bigdata_position_bak where objecttype = '5' and positiontype = '1') b on a.cityid = b.cityid and a.commid = b.objectid left join bigdata_district_bak c on a.cityid=c.cityid and a.distid=c.distid where a.cityid = '{cityid}'"
queryse = cr.execute(sql)
columns = [i[0].lower() for i in queryse.description]
rs = cr.fetchall()
data_df = pd.DataFrame(rs,columns=columns)
return data_df
def avm_price_copy(cityid,yearmonth):
sql = f"insert into t_app_p9pha_plda.avm_community_base_price_gj_h_copy select * from t_app_p9pha_plda.avm_community_base_price_gj_h where urbn_id='{cityid}' and gujiabds_clc_yrmo_val={yearmonth}"
pgdb.sql_execute(sql)
def get_sample(cityid):
sql = f"select urbn_id,gujia_comm_id,comm_nm,gujia_bds_unitprc,guiabconstructionarea from base.t0831_bigdata_forsale_gj_h where urbn_id='{cityid}' and gujia_hs_src_dtsrc in ('1','4') and anc_tm >= TO_DATE('2023-04-01','YYYY-MM-DD')"
data_df = pgdb.read(sql)
return data_df
def get_deal(cityid):
sql = f"select urbn_id,gujia_comm_id,comm_nm,guiabconstructionarea,gujia_bds_trdtckt_prc from base.t0831_bigdata_deal_gj_h where urbn_id='{cityid}' and txn_dt >= TO_DATE('2024-03-01','YYYY-MM-DD') and txn_dt < TO_DATE('2024-04-01','YYYY-MM-DD')"
data_df = pgdb.read(sql)
data_df = data_df.rename(columns={'urbn_id': 'cityid','gujia_comm_id': '_id','comm_nm': 'name', 'guiabconstructionarea': 'area','gujia_bds_trdtckt_prc': 'deal_price'})
return data_df
def get_deal_data(cityid):
sql = f"select * from base.t0831_bigdata_deal_gj_h where urbn_id='{cityid}' and txn_dt >= TO_DATE('2024-03-01','YYYY-MM-DD') and txn_dt < TO_DATE('2024-04-01','YYYY-MM-DD')"
data_df = pgdb.read(sql)
return data_df
def get_region_price(cityid,yearmonth):
sql = f"select urbn_id,gujia_admndiv_id,gxda_admndiv_nm,gujia_bds_urbn_avprc from t_app_p9pha_plda.avm_district_price_gj_h where urbn_id='{cityid}' and gujiabds_clc_yrmo_val={yearmonth}"
data_df = pgdb.read(sql)
data_df = data_df.rename(columns={'urbn_id': 'cityid','gujia_admndiv_id': 'district_id','gxda_admndiv_nm': 'district_name', 'gujia_bds_urbn_avprc': 'district_price'})
return data_df
def get_evaluation_third_price(cityid,yearmonth,type='第三方'):
sql = f"select urbn_id,gujia_comm_id,gujiabds_to_mkprc_mny from t_app_p9pha_plda.avm_evaluation_item_gj_h where urbn_id='{cityid}' and gujiabds_clc_yrmo_val={yearmonth} and gujia_data_tp='{type}' "
data_df = pgdb.read(sql)
data_df = data_df.rename(columns={'urbn_id': 'cityid','gujiabds_to_mkprc_mny': 'third_price','gujia_comm_id':'_id'})
return data_df
def get_third_price(cityid,yearmonth):
sql = f"select urbn_id,gujia_bds_id,comm_nm,gujia_dtsr_dsc,gujia_bds_comm_avprc from base.t0831_bigdata_third_party_price_gj_h where urbn_id='{cityid}' and gujiabds_avprc_dt_val={yearmonth} and gujia_dtsr_dsc in ('链家','安居客') "
data_df = pgdb.read(sql)
data_df = data_df.rename(columns={'urbn_id': 'cityid','gujia_bds_id': '_id','gujia_dtsr_dsc': 'source','gujia_bds_comm_avprc': 'price'})
return data_df
if __name__ == '__main__':
city='常州'
yearmonth=202302
get_community_base_price(city=city,yearmonth=yearmonth)
+49
View File
@@ -0,0 +1,49 @@
import pandas as pd
from dags.configs.citymap import city_name_id_map
from pqsql_connect import get_community_base_price,get_evaluation_third_price,get_third_price
from mongodb_connect import get_district_stat_on,get_seaweed,get_gxd_price
yearmonth='202404'
latest_year_month = '202403'
df_concat = pd.DataFrame()
for city in city_name_id_map:
print(city)
city_id = city_name_id_map[city]
base_price = get_community_base_price(city_id, yearmonth=yearmonth)
base_price.rename(columns={'price': '当月均价', 'type': '计算方式'}, inplace=True)
base_price_last = get_community_base_price(city_id, yearmonth=latest_year_month)
base_price_last.rename(columns={'price': '上月均价', 'type': '上月计算方式'}, inplace=True)
get_evaluation_third_price_df = get_evaluation_third_price(city_id, yearmonth=yearmonth,type='第三方')
get_evaluation_third_price_df.rename(columns={'third_price': '第三方对标价格'}, inplace=True)
deal_price_df = get_evaluation_third_price(city_id, yearmonth=yearmonth,type='成交')
deal_id = deal_price_df['_id'].tolist()
get_evaluation_third_price_df = get_evaluation_third_price_df[~(get_evaluation_third_price_df['_id'].isin(deal_id))]
third_price = get_third_price(cityid=city_id, yearmonth=latest_year_month)
lianjia_price =third_price[third_price['source']=='链家'].drop_duplicates(subset=["_id"], keep="first")
lianjia_price.rename(columns={'price': '链家价格'}, inplace=True)
anjuke_price =third_price[third_price['source']=='安居客'].drop_duplicates(subset=["_id"], keep="first")
anjuke_price.rename(columns={'price': '安居客价格'}, inplace=True)
base_price_gj = get_district_stat_on(city)
seaweed_df = get_seaweed(city)
seaweed_df['_id'] = seaweed_df['_id'].astype('str')
if base_price_gj.empty:
continue
base_price_gj = base_price_gj.merge(seaweed_df[['_id', 'region', 'name']], on=['region', 'name'], how='left')
base_price_gj.rename(columns={'avg_price': '房价网2C价格', 'avg_price_2b': '房价网2B价格'}, inplace=True)
base_price_gxd = get_gxd_price()
base_price_gxd.rename(columns={'district_name': 'name', 'price': '国信达价格'}, inplace=True)
data_df_temp = seaweed_df[['_id','city', 'region', 'name']].merge(base_price_gxd[['city', 'region', 'name', '国信达价格', 'c_date']], on=['city', 'region', 'name'])
data_df_temp = data_df_temp.sort_values(by="c_date", ascending=False)
data_df_temp = data_df_temp.drop_duplicates(subset=["city", "region", "name"], keep="first")
if base_price.empty or base_price_last.empty or get_evaluation_third_price_df.empty:
continue
price_merge = base_price.merge(base_price_last[['_id', '上月均价', '上月计算方式']], on='_id', how='left')
price_merge = price_merge.merge(get_evaluation_third_price_df[['_id','第三方对标价格']],on='_id')
price_merge = price_merge.merge(lianjia_price[['_id','链家价格']],on='_id',how='left')
price_merge = price_merge.merge(anjuke_price[['_id','安居客价格']],on='_id',how='left')
price_merge = price_merge.merge(base_price_gj[['_id','房价网2C价格','房价网2B价格']], on='_id', how='left')
price_merge = price_merge.merge(data_df_temp[['_id','国信达价格']], on='_id', how='left')
price_merge.rename(columns={'city': '城市', 'district': '区域', '_id': '小区ID', 'name': '小区名','yearmonth':'月份'}, inplace=True)
df_concat = pd.concat([df_concat,price_merge])
df_concat.to_excel('小区第三方均价输出.xlsx', encoding='utf-8', index=False)