parseCreditPdf.py0615 152 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130
  1. #coding=utf-8
  2. import shutil
  3. import pdfplumber
  4. import pandas as pd
  5. import numpy as np;
  6. import sys
  7. import os
  8. import traceback
  9. from prp import PrpCrypt
  10. #指标相关
  11. import loanIndexParser as lip;
  12. import payRcdIndexParser as prp;
  13. import creditCardIndexParser as cip
  14. import queryInfoIndexParser as qip
  15. import requests
  16. import utils;
  17. import time;
  18. import consts;
  19. import math
  20. import dfParser;
  21. import gc
  22. import json
  23. from dbController import DbController
  24. from pboc.invokePboc import PBOC
  25. from ini_op import Config;
  26. base_dir = os.path.dirname(os.path.abspath(__file__))
  27. config = Config(base_dir+"/config.ini");
  28. #连接数据库
  29. dbController = DbController();
  30. pd.set_option('mode.chained_assignment', None)
  31. import log
  32. logger = log.logger
  33. # 查询信息
  34. dfMap = {};
  35. allHeaders = [] # 所有表头
  36. queryInfoDf = pd.DataFrame();
  37. queryInfoDf_header = ["被查询者姓名", "被查询者证件类型", "被查询者证件号码", "查询机构", "查询原因"];
  38. dfMap["queryInfoDf"] = {"df": queryInfoDf, "nextDf": None};
  39. allHeaders.append(queryInfoDf_header);
  40. # 身份信息
  41. identityDf = pd.DataFrame();
  42. identity_header = ['性别', '出生日期', '婚姻状况', '学历', '学位', '就业状况', '国籍', '电子邮箱']
  43. addressDf = pd.DataFrame(); # 通讯地址
  44. dfMap["identityDf"] = {"df": identityDf, "nextDf": None, "mobiles": None};
  45. allHeaders.append(identity_header);
  46. # 配偶信息
  47. mateDf = pd.DataFrame();
  48. mateDf_header = ['姓名', '证件类型', '证件号码', '工作单位', '联系电话']
  49. dfMap["mateDf"] = {"df": mateDf, "nextDf": None};
  50. allHeaders.append(mateDf_header);
  51. # 居住信息====暂时该信息没有用到先不解析
  52. liveInfoDf = pd.DataFrame();
  53. liveInfoDf_header = ['编号', '居住地址', '住宅电话', '居住状况', '信息更新日期']
  54. dfMap["liveInfoDf"] = {"df": liveInfoDf, "nextDf": None};
  55. allHeaders.append(liveInfoDf_header);
  56. # 职业信息
  57. occupationDf = pd.DataFrame();
  58. occupationInfo_header = ['编号', '工作单位', '单位性质', '单位地址', '单位电话']
  59. occupationInfo_header1 = ['编号', '职业', '行业', '职务', '职称', '进入本单位年份', '信息更新日期']
  60. dfMap["occupationDf"] = ({"df": occupationDf, "nextDf": None});
  61. # allHeaders.append(occupationInfo_header1);
  62. allHeaders.append(occupationInfo_header);
  63. # 上次查询记录
  64. preQueryRcd_header0 = ['上一次查询记录']
  65. allHeaders.append(preQueryRcd_header0);
  66. # 查询记录概要
  67. # queryInfoBriefDf = pd.DataFrame();
  68. # queryInfoBrief_header0 = ['最近1个月内的查询机构数', '最近1个月内的查询次数', '最近2年内的查询次数']
  69. # queryInfoBrief_header1 = ['贷款审批', '信用卡审批', '贷款审批', '信用卡\n审批', '本人查询', '贷后管理', '担保资格\n审查', '特约商户\n实名审查']
  70. # dfMap["queryInfoBriefDf"] = ({"df": queryInfoBriefDf, "nextDf": None});
  71. # allHeaders.append(queryInfoBrief_header0);
  72. # allHeaders.append(queryInfoBrief_header1);
  73. # 信贷交易信息提示
  74. loanTradeInfoDf = pd.DataFrame();
  75. loanTradeInfo_header = ['业务类型', '账户数', '首笔业务发放月份'];
  76. dfMap["loanTradeInfoDf"] = ({"df": loanTradeInfoDf, "nextDf": None});
  77. allHeaders.append(loanTradeInfo_header)
  78. # 信贷交易违约信息概要
  79. # 被追偿信息汇总 资产处置和垫款业务
  80. recoveryInfoSumDf = pd.DataFrame();
  81. recoveryInfoSumDf_header = ['业务种类', '账户数', '余额'];
  82. dfMap["recoveryInfoSumDf"] = ({"df": recoveryInfoSumDf, "nextDf": None});
  83. allHeaders.append(recoveryInfoSumDf_header)
  84. # 呆账信息汇总
  85. badDebtsInfoSumDf = pd.DataFrame();
  86. badDebtsInfoSumDf_header = ['账户数', '余额']; # 被追偿信息汇总
  87. dfMap["badDebtsInfoSumDf"] = ({"df": badDebtsInfoSumDf, "nextDf": None});
  88. allHeaders.append(badDebtsInfoSumDf_header)
  89. # 逾期透资信息汇总
  90. overdueInfoSumDf = pd.DataFrame();
  91. overdueInfoSumDf_header = ['账户类型', '账户数', '月份数', '单月最高逾期/透支总额', '最长逾期/透支月数']
  92. dfMap["overdueInfoSumDf"] = ({"df": overdueInfoSumDf, "nextDf": None});
  93. allHeaders.append(overdueInfoSumDf_header)
  94. # 非循环贷账户信息汇总
  95. loanAccountInfoSumDf = pd.DataFrame();
  96. loanAccountInfoSumDf_header0 = ['非循环贷账户信息汇总']
  97. loanAccountInfoSumDf_header1 = ['管理机构数', '账户数', '授信总额', '余额', '最近6个月平均应还款']
  98. dfMap["loanAccountInfoSumDf"] = ({"df": loanAccountInfoSumDf, "nextDf": None});
  99. allHeaders.append(loanAccountInfoSumDf_header0)
  100. allHeaders.append(loanAccountInfoSumDf_header1)
  101. # 循环额度下分账户信息汇总
  102. cycleCreditAccountInfoSumDf = pd.DataFrame();
  103. cycleCreditAccountInfoSumDf_header0 = ['循环额度下分账户信息汇总']
  104. cycleCreditAccountInfoSumDf_header1 = ['管理机构数', '账户数', '授信总额', '余额', '最近6个月平均应还款'],
  105. dfMap["cycleCreditAccountInfoSumDf"] = ({"df": cycleCreditAccountInfoSumDf, "nextDf": None});
  106. allHeaders.append(cycleCreditAccountInfoSumDf_header0)
  107. allHeaders.append(cycleCreditAccountInfoSumDf_header1)
  108. # 循环贷账户信息汇总
  109. cycleLoanAccountInfoSumDf = pd.DataFrame();
  110. cycleLoanAccountInfoSumDf_header0 = ['循环贷账户信息汇总']
  111. cycleLoanAccountInfoSumDf_header1 = ['管理机构数', '账户数', '授信总额', '余额', '最近6个月平均应还款']
  112. dfMap["cycleLoanAccountInfoSumDf"] = ({"df": cycleLoanAccountInfoSumDf, "nextDf": None});
  113. allHeaders.append(cycleLoanAccountInfoSumDf_header0)
  114. allHeaders.append(cycleLoanAccountInfoSumDf_header1)
  115. # 贷记卡账户信息汇总
  116. creditCardInfoSumDf = pd.DataFrame();
  117. creditCardInfoSumDf_header0 = ['贷记卡账户信息汇总']
  118. creditCardInfoSumDf_header1 = ['发卡机构数', '账户数', '授信总额', '单家机构最高\n授信额', '单家机构最低\n授信额', '已用额度', '最近6个月平\n均使用额度']
  119. dfMap["creditCardInfoSumDf"] = ({"df": creditCardInfoSumDf, "nextDf": None});
  120. allHeaders.append(creditCardInfoSumDf_header0)
  121. allHeaders.append(creditCardInfoSumDf_header1)
  122. # 准贷记卡账户信息汇总
  123. creditCardInfoSumDfZ = pd.DataFrame();
  124. creditCardInfoSumDfZ_header0 = ['准贷记卡账户信息汇总']#'准贷记卡账户信息汇总'
  125. creditCardInfoSumDfZ_header1 = ['发卡机构数', '账户数', '授信总额', '单家机构最高\n授信额', '单家机构最低\n授信额', '透支余额', '最近6个月平\n均透支余额']
  126. dfMap["creditCardInfoSumDfZ"] = ({"df": creditCardInfoSumDfZ, "nextDf": None});
  127. allHeaders.append(creditCardInfoSumDfZ_header0)
  128. allHeaders.append(creditCardInfoSumDfZ_header1)
  129. #公共信息概要
  130. publicInfoBriefDf = pd.DataFrame();
  131. publicInfoBriefDf_header0 = ['公共信息汇总']
  132. dfMap["publicInfoBriefDf"] = ({"df": publicInfoBriefDf, "nextDf": None});
  133. allHeaders.append(publicInfoBriefDf_header0)
  134. #查询记录汇总
  135. queryRecordSumDf_header0=['最近1个月内的查询机构数', '最近1个月内的查询次数', '最近2年内的查询次数']
  136. queryRecordSumDf = pd.DataFrame();
  137. dfMap["queryRecordSumDf"] = ({"df": queryRecordSumDf, "nextDf": None});
  138. allHeaders.append(queryRecordSumDf_header0)
  139. # 非循环贷账户,循环额度下分账户
  140. # 循环贷账户
  141. loan_header = ['管理机构', '账户标识', '开立日期', '到期日期', '借款金额', '账户币种']
  142. loanDfs = [];
  143. dfMap["loanDfs"] = ({"dfs": loanDfs, "nextDf": []});
  144. allHeaders.append(loan_header)
  145. # 贷记卡账户
  146. creditCard_header = ['发卡机构', '账户标识', '开立日期', '账户授信额度', '共享授信额度', '币种', '业务种类', '担保方式']
  147. creditCardDfs = [];
  148. dfMap["creditCardDfs"] = ({"dfs": creditCardDfs, "nextDf": []});
  149. allHeaders.append(creditCard_header)
  150. # 准备贷记卡账户
  151. creditCardZ_header = ['发卡机构', '账户标识', '开立日期', '账户授信额度', '共享授信额度', '币种', '担保方式']
  152. creditCardDfsZ = [];
  153. dfMap["creditCardDfsZ"] = ({"dfs": creditCardDfsZ, "nextDf": []});
  154. allHeaders.append(creditCardZ_header)
  155. #
  156. # 相关还款责任信息汇总 未使用到
  157. # 信贷交易信息明细
  158. # 被追偿信息 未使用到
  159. recoveryInfoDfs_header = ['管理机构','业务种类','债权接收日期','债权金额','债权转移时的还款状态']
  160. recoveryInfoDfs = [];
  161. dfMap["recoveryInfoDfs"] = ({"dfs": recoveryInfoDfs, "nextDf": []});
  162. allHeaders.append(recoveryInfoDfs_header)
  163. # 公共信息明细
  164. # 强制执行记录
  165. forceExecRcdDfs_header = ['编号', '执行法院', '执行案由', '立案日期', '结案方式']
  166. forceExecRcdDfs = [];
  167. dfMap["forceExecRcdDfs"] = ({"dfs": forceExecRcdDfs, "nextDf": []});
  168. allHeaders.append(forceExecRcdDfs_header)
  169. # 查询记录
  170. queryRecordDetailDf_header = ['编号', '查询日期', '查询机构', '查询原因']
  171. dfMap["queryRecordDetailDf"] = ({"df": pd.DataFrame(), "nextDf": []});
  172. allHeaders.append(queryRecordDetailDf_header)
  173. #住房公积金参缴记录
  174. housingFundRcdDfs_header =['参缴地', '参缴日期', '初缴月份', '缴至月份', '缴费状态', '月缴存额', '个人缴存比例', '单位缴存比例']
  175. housingFundRcdDfs = []
  176. dfMap["housingFundRcdDfs"] = ({"dfs": housingFundRcdDfs, "nextDf": []});
  177. allHeaders.append(housingFundRcdDfs_header)
  178. repaymentSumDf_header0=['相关还款责任信息汇总']
  179. dfMap["repaymentSumDf"] = ({"df": pd.DataFrame(), "nextDf": None});
  180. allHeaders.append(repaymentSumDf_header0)
  181. # 处理分页思路
  182. # df估计得放到对象里面,然后存储下一个df,一个对象里包含key
  183. # 然后判断对象的df的完整性,如果不完整代表被分页了,把nextdf合并到当前的df
  184. # 针对可合并的列的场景
  185. # =======
  186. keyList = [] # 存储所有的df的key列表
  187. # pd.Series()
  188. # 检查数据是否带表头
  189. # 应该是每一页开头的一行和每个表头对比一次,确认是不是表头,或者表头有什么共同的规律也可以看下
  190. import timeit
  191. # 定义指标部分======================start
  192. reportTime = ""; # 报告时间
  193. # 被查询者姓名
  194. queryInfoName = "";
  195. queryInfoCardId = "" # 被查询者证件号码
  196. # 定义指标部分======================end
  197. # 被查询信息-基础信息
  198. # 报告时间
  199. # 被查询者姓名
  200. # 被查询者证件号码
  201. # 基础信息
  202. queryInfo = {"reportTime":"","queryInfoCardId":""}
  203. # 身份信息
  204. identity = {}
  205. # 配偶信息
  206. mate = {}
  207. # 信贷交易信息提示-信用提示
  208. loanTradeInfo = {'perHouseLoanAccount': 0, 'perBusHouseLoanAccount': 0, 'otherLoanAccount': 0, 'loanMonthMin': 0,
  209. 'creditCardMonthMin': 0, 'creditAccount': 0, 'creditAccountZ': 0}
  210. # 逾期及违约信息概要
  211. overdueBrief = {}
  212. # 逾期及透资信息汇总
  213. # 贷款逾期账户数 loanOverdueAccount
  214. # 贷款逾期月份数 loanOverdueMonth
  215. # 贷款单月最高逾期总额 loanCurMonthOverdueMaxTotal
  216. # 贷款最长逾期月数 loanMaxOverdueMonth
  217. overdueInfo = {"loanOverdueAccount": "", "loanOverdueMonth": "", "loanCurMonthOverdueMaxTotal": "",
  218. "loanMaxOverdueMonth": "",
  219. "creditCardOverdueAccount": "", "creditCardOverdueMonth": "", "creditCardCurMonthOverdueMaxTotal": "",
  220. "creditCardMaxOverdueMonth": ""}
  221. # 未结清贷款信息汇总
  222. # ['管理机构数', '账户数', '授信总额', '余额', '最近6个月平均应还款']
  223. loanAccountInfoSum = {"mgrOrgCount": 0, "account": 0, "creditTotalAmt": 0, "balance": 0, "last6AvgPayAmt": 0}
  224. # 未销户贷记卡发卡法人机构数
  225. # 未销户贷记卡发卡机构数
  226. # 未销户贷记卡账户数
  227. # 未销户贷记卡授信总额
  228. # 未销户贷记卡单家行最高授信额
  229. # 未销户贷记卡单家行最低授信额
  230. # 未销户贷记卡已用额度
  231. # 未销户贷记卡近6月平均使用额度
  232. # 未结清贷记卡信息汇总
  233. # ['发卡机构数', '账户数', '授信总额', '单家机构最高\n授信额', '单家机构最低\n授信额', '已用额度', '最近6个月平\n均使用额度']
  234. creditCardInfoSum = {"awardOrgCount": 0, "account": 0, "creditTotalAmt": 0, "perMaxCreditTotalAmt": 0,
  235. "perMinCreditTotalAmt": 0, "useAmt": 0, "last6AvgUseAmt": 0}
  236. # 信 贷 审 批 查 询 记 录 明 细
  237. queryRecordDetail = {"last1MonthQueryTimes": 0, "last3MothLoanApproveTimes": 0, "last3MonthQueryTimes": 0,
  238. "lastTimeLoanApproveMonth": 0}
  239. #最近一笔结清贷款的贷款金额 
  240. loanAccountInfo = {"lastSettleLoanAmt": 0}
  241. loanAccountDfs=[];#横向合并
  242. creditCardAccountDfs=[];#贷记卡账户合并
  243. creditCardAccountDfsZ=[];#准贷记卡账户合并
  244. recoveryInfoAccountDfs=[];#被追偿账户合并
  245. housingFundRcdAccountDfs=[];#公积金账户合并
  246. #============================指标定义区 start=============================
  247. #基本信息 拆分
  248. # basicInfoDf = pd.DataFrame(columns=consts.basicInfoHeader, index=[0])
  249. #身份信息
  250. identityInfoIndex = '身份信息'
  251. identityInfoDf = pd.DataFrame(columns=consts.identityInfoHeader,index=[identityInfoIndex])
  252. #配偶信息
  253. mateInfoIndex = '配偶信息'
  254. mateInfoDf = pd.DataFrame(columns=consts.mateInfoHeader,index=[mateInfoIndex])
  255. #居住信息
  256. liveInfoIndex = '居住信息'
  257. liveInfoDf = pd.DataFrame(columns=consts.liveInfoHeader,index=[liveInfoIndex])
  258. #职业信息
  259. occupationInfoIndex = '职业信息'
  260. occupationInfoDf = pd.DataFrame(columns=consts.occupationInfoHeader,index=[occupationInfoIndex])
  261. #信贷交易信息提示
  262. loanTradeInfoIndex = '信贷交易信息提示'
  263. briefInfoDf_loanTradeInfo = pd.DataFrame(columns=consts.briefInfoHeader_loanTradeInfo,index=[loanTradeInfoIndex])
  264. #被追偿信息汇总及呆账信息汇总
  265. recoveryInfoSumIndex = '信贷交易违约信息概要'
  266. briefInfoDf_recoveryInfoSum = pd.DataFrame(columns=consts.briefInfoHeader_recoveryInfo,index=[recoveryInfoSumIndex])
  267. #呆账信息汇总
  268. badDebtsInfoIndex = '呆账信息汇总'
  269. briefInfoDf_badDebtsInfoSum = pd.DataFrame(columns=consts.briefInfoHeader_badDebtsInfoSum,index=[badDebtsInfoIndex])
  270. #逾期(透支)信息汇总
  271. overdueInfoSumIndex='逾期(透支)信息汇总'
  272. briefInfoDf_overdueInfoSum = pd.DataFrame(columns=consts.briefInfoHeader_overdueInfoSum,index=[overdueInfoSumIndex])
  273. #信贷交易授信及负债信息概要
  274. loanTradeCreditInfoIndex='信贷交易授信及负债信息概要'
  275. briefInfoDf_loanTradeCreditInfo = pd.DataFrame(columns=consts.briefInfoHeader_loanTradeCreditInfo,index=[loanTradeCreditInfoIndex]).fillna(0.0)
  276. #公共信息概要
  277. publicInfoBriefIndex = '公共信息概要'
  278. publicInfoBriefDf = pd.DataFrame(columns=consts.publicInfoBriefHeader,index=[publicInfoBriefIndex])
  279. #查询记录汇总
  280. queryRecordSumIndex = '查询记录汇总'
  281. queryRecordSumDf = pd.DataFrame(columns=consts.queryRecordSumHeader,index=[queryRecordSumIndex])
  282. #信贷交易明细-被追偿信息
  283. recoveryInfoIndex='被追偿信息'
  284. creditTradeDetailDf_recoveryInfo = pd.DataFrame(columns=consts.creditTradeDetailHeader_recoveryInfo,index=[recoveryInfoIndex])
  285. #信贷交易明细-特殊交易
  286. specialTradeIndex='特殊交易'
  287. creditTradeDetailHeader_specialTrade = pd.DataFrame(columns=consts.creditTradeDetailHeader_specialTrade,index=[specialTradeIndex])
  288. #信贷交易明细
  289. #非循环贷账户
  290. loanInfoIndex='非循环贷账户'
  291. creditTradeDetailDf_loanAccountInfo = pd.DataFrame(columns=consts.creditTradeDetailHeader_loanAccountInfo,index=[loanInfoIndex])
  292. #循环额度下分账户
  293. cycleCreditAccountInfoIndex='循环额度下分账户'
  294. creditTradeDetailDf_cycleCreditAccountInfo = pd.DataFrame(columns=consts.creditTradeDetailHeader_cycleCreditAccountInfo,index=[cycleCreditAccountInfoIndex])
  295. #循环贷账户
  296. cycleLoanAccountInfoIndex='循环贷账户'
  297. creditTradeDetailDf_cycleLoanAccountInfo = pd.DataFrame(columns=consts.creditTradeDetailHeader_cycleLoanAccountInfo,index=[cycleLoanAccountInfoIndex])
  298. #贷款信息
  299. loanAccountInfoIndex='贷款信息'
  300. loanAccountInfoDf = pd.DataFrame(columns=consts.loanAccountInfoHeader,index=[loanAccountInfoIndex])
  301. #贷记卡信息
  302. creditCardAccountInfoIndex = '贷记卡账户'
  303. creditCardAccountInfoDf = pd.DataFrame(columns=consts.creditCardAccountInfoHeader,index=[creditCardAccountInfoIndex])
  304. #准贷记卡
  305. creditCardAccountInfoIndexZ = '准贷记卡账户'
  306. creditCardAccountInfoDfZ = pd.DataFrame(columns=consts.creditCardAccountInfoHeaderZ,index=[creditCardAccountInfoIndexZ])
  307. useRateIndex = '使用率'
  308. useRateDf = pd.DataFrame(columns=consts.creditTradeDetailHeader_useRate,index=[useRateIndex])
  309. openAccountIndex = '开户数'
  310. openAccountDf = pd.DataFrame(columns=consts.creditTradeDetailHeader_openAccount,index=[openAccountIndex])
  311. payRcdStatusIndex = '24期还款状态'
  312. payRcdStatusDf = pd.DataFrame(columns=consts.creditTradeDetailHeader_payRcdStatus,index=[payRcdStatusIndex])
  313. #查询记录明细指标
  314. queryRecordDetailIndex = '信贷审批查询记录明细'
  315. queryRecordDetailDf = pd.DataFrame(columns=consts.queryRecordDetailHeader,index=[queryRecordDetailIndex])
  316. #住房公积金
  317. housingFundRcdIndex = '住房公积金参缴记录'
  318. housingFundRcdDf = pd.DataFrame(columns=consts.housingFundRcdHeader,index=[housingFundRcdIndex])
  319. #============================指标定义区 end=============================
  320. # 解析被查询信息指标
  321. def parseQueryInfo(dfObj):
  322. df = dfObj["df"];
  323. reportTime = df.loc[0, :][3]
  324. reportTime = reportTime.split(":")[1]
  325. reportTime = reportTime.replace(".", "-"); # 报告时间
  326. queryInfo["reportTime"] = reportTime
  327. row = df.loc[2, :]
  328. queryInfo["queryInfoName"] = row[0]; # 被查询者姓名
  329. # basicInfoDf.loc[0, '姓名'] = row[0]
  330. queryInfo["queryInfoCardId"] = row[2].replace("\n", ""); # 被查询者证件号码
  331. # basicInfoDf.loc[0, '身份证'] = row[2].replace("\n", "")
  332. # 婚姻状况
  333. # 学历
  334. # 单位电话
  335. # 住宅电话
  336. # 通讯地址
  337. def parseIdentity(dfObj):
  338. df = dfObj["df"];
  339. if not df.empty:
  340. row1 = df.loc[1, :].dropna().reset_index(drop=True)
  341. # identity["marital"] = row1[3] # 婚姻状况
  342. # identity["education"] = row1[4] # 学历
  343. # identity["commAddress"] = row1[9].replace("\n", ""); # 通讯地址
  344. identityInfoDf.loc[identityInfoIndex, '性别'] = row1[0]
  345. identityInfoDf.loc[identityInfoIndex, '出生日期'] = dfParser.formatDate(row1[1])[0:7]
  346. identityInfoDf.loc[identityInfoIndex, '国籍'] = row1[6]
  347. identityInfoDf.loc[identityInfoIndex, '户籍地址'] = row1[9].replace("\n", "")
  348. identityInfoDf.loc[identityInfoIndex, '婚姻状况'] = row1[2]
  349. identityInfoDf.loc[identityInfoIndex, '学历'] = row1[3].replace("\n", "")
  350. identityInfoDf.loc[identityInfoIndex, '学位'] = row1[4]
  351. identityInfoDf.loc[identityInfoIndex, '通讯地址'] = row1[8].replace("\n", "")
  352. identityInfoDf.loc[identityInfoIndex, '就业状况'] = row1[5]
  353. mobileDf = dfObj["mobileDf"];
  354. identityInfoDf.loc[identityInfoIndex, '历史手机号码数'] = mobileDf.index.size
  355. reportTime = queryInfo["reportTime"]
  356. identityInfoDf.loc[identityInfoIndex, '近3个月手机号码数'] = getLastMonthMobileCount(mobileDf,3,reportTime)
  357. identityInfoDf.loc[identityInfoIndex, '近6个月手机号码数'] = getLastMonthMobileCount(mobileDf, 6,reportTime)
  358. identityInfoDf.loc[identityInfoIndex, '近12个月手机号码数'] = getLastMonthMobileCount(mobileDf, 12,reportTime)
  359. identityInfoDf.loc[identityInfoIndex, '近24个月手机号码数'] = getLastMonthMobileCount(mobileDf, 24,reportTime)
  360. #最近几个月电话号码数
  361. def getLastMonthMobileCount(df, month,reportTime):
  362. # 当前日期
  363. last1MonthDateStr = reportTime
  364. # 最近一个月
  365. lastMonthDate = np.datetime64(last1MonthDateStr, "D") - np.timedelta64(30 * month, 'D')
  366. lastMonthMobileDf = df[df[5] >= str(lastMonthDate)]
  367. return lastMonthMobileDf.shape[0];
  368. # 配偶姓名
  369. # 配偶证件号码
  370. # 配偶工作单位
  371. # 配偶联系电话
  372. def parseMate(dfObj):
  373. df = dfObj["df"];
  374. if not df.empty:
  375. row1 = df.loc[1, :]
  376. mate["mateName"] = row1[0] # 配偶姓名
  377. mate["mateCardId"] = row1[2] # 配偶证件号码
  378. mate["mateWorkCompany"] = row1[3].replace("\n", ""); # 配偶工作单位
  379. mate["mateContactTel"] = row1[4]; # 配偶联系电话
  380. mateInfoDf.loc[mateInfoIndex, '姓名'] = row1[0]
  381. mateInfoDf.loc[mateInfoIndex, '证件号码'] = row1[2]
  382. mateInfoDf.loc[mateInfoIndex, '工作单位'] = row1[3].replace("\n", "");
  383. mateInfoDf.loc[mateInfoIndex, '联系电话'] = row1[4].replace("\n", "");
  384. #解析居住信息
  385. def parseLiveInfo(dfObj):
  386. df = dfObj["df"];
  387. if not df.empty:
  388. row1 = df.loc[1, :]
  389. liveInfoDf.loc[liveInfoIndex, '居住地址'] = row1[1]
  390. liveInfoDf.loc[liveInfoIndex, '住宅电话'] = row1[2]
  391. liveInfoDf.loc[liveInfoIndex, '历史居住地址个数'] = df.index.size-1;
  392. curDate = np.datetime64(time.strftime("%Y-%m-%d"));
  393. last3year = str(curDate)[0:4]
  394. last3yearDate = str(int(last3year)-3)+str(curDate)[4:10]
  395. lastLiveDf = df[df[4]>=last3yearDate];
  396. liveInfoDf.loc[liveInfoIndex, '最近3年内居住地址个数'] = lastLiveDf.index.size-1;
  397. houseIndex = df[df[3]=='自置'].index.size>0
  398. if (houseIndex):
  399. houseStr = '是'
  400. else:
  401. houseStr= '否'
  402. liveInfoDf.loc[liveInfoIndex, '当前居住状况-是否具有自有住房'] = houseStr;
  403. liveInfoDf.loc[liveInfoIndex, '居住状况'] = row1[3]
  404. liveInfoDf.loc[liveInfoIndex, '信息更新日期'] = row1[4]
  405. #解析职业信息
  406. def parseOccupationInfoDf(dfObj):
  407. df = dfObj["df"];
  408. if not df.empty:
  409. occIndex1 = 0#判断职业从哪行开始
  410. for i in range(0,df.index.size):
  411. if df.loc[i,:].dropna().tolist()==occupationInfo_header1:
  412. occIndex1=i;
  413. break;
  414. occDf = df[1:occIndex1].reset_index(drop=True)#工作单位
  415. occDfNew = pd.DataFrame()
  416. occDf1New = pd.DataFrame()
  417. #删除为none的列 合并的bug TODO
  418. for i in range(0,occDf.index.size):
  419. occDfNew = occDfNew.append([pd.DataFrame(occDf.iloc[i].dropna().reset_index(drop=True)).T],ignore_index=True)
  420. occDf1 = df[occIndex1+1:df.index.size].reset_index(drop=True) #职业
  421. for i in range(0,occDf1.index.size):
  422. occDf1New = occDf1New.append([pd.DataFrame(occDf1.iloc[i].dropna().reset_index(drop=True)).T], ignore_index=True)
  423. occDf = pd.concat([occDfNew, occDf1New], axis=1, ignore_index=True)#合并df
  424. row = occDf.loc[0, :].dropna()#取最新
  425. occupationInfoDf.loc[occupationInfoIndex, '工作单位'] = row[1]
  426. last3yearDate = utils.getLastMonthDate(queryInfo['reportTime'],12*3)
  427. occDf = utils.replaceDateColIdx(occDf,occDf.columns.size-1)
  428. dateIndex = occDf.columns.size-1;#日期列
  429. last3yearOccDf = occDf[occDf[dateIndex]>=last3yearDate]
  430. occupationInfoDf.loc[occupationInfoIndex, '最近3年内工作单位数'] = last3yearOccDf.index.size;
  431. occupationInfoDf.loc[occupationInfoIndex, '单位电话'] = row[4];
  432. reportTime = queryInfo['reportTime']
  433. try:
  434. minDateIndex = np.argmin(occDf[dateIndex]);
  435. maxDateIndex = np.argmax(occDf[dateIndex]);
  436. rowYearMin = occDf.loc[minDateIndex, :].dropna()
  437. rowYearMax = occDf.loc[maxDateIndex, :].dropna()
  438. if rowYearMin[10]!="--":
  439. occupationInfoDf.loc[occupationInfoIndex, '最早进入本单位年份距报告日期时长'] = int(str(np.datetime64(reportTime, "Y")))-int(rowYearMin[10])
  440. if rowYearMax[10]!="--":
  441. occupationInfoDf.loc[occupationInfoIndex, '最新进入本单位年份距报告日期时长'] = int(str(np.datetime64(reportTime, "Y")))-int(rowYearMax[10])
  442. except:
  443. logger.error("最早进入本单位年份距报告日期时长解析异常")
  444. row0 = occDf.loc[0,:].dropna().reset_index(drop=True)#最新
  445. occupationInfoDf.loc[occupationInfoIndex, '单位性质'] =row0[2]
  446. occupationInfoDf.loc[occupationInfoIndex, '单位地址'] = row0[3].replace("\n","")
  447. occupationInfoDf.loc[occupationInfoIndex, '职业'] = row0[6]
  448. occupationInfoDf.loc[occupationInfoIndex, '行业'] = row0[7]
  449. occupationInfoDf.loc[occupationInfoIndex, '职务'] = row0[8]
  450. occupationInfoDf.loc[occupationInfoIndex, '职称'] = row0[9]
  451. occupationInfoDf.loc[occupationInfoIndex, '进入本单位年份'] = row0[10]
  452. occupationInfoDf.loc[occupationInfoIndex, '信息更新日期'] = row0[11]
  453. occupationInfoDf.loc[occupationInfoIndex, '历史工作单位数'] = occDf1.index.size
  454. # 日期相减离当前时间月份
  455. # 贷款账龄(月数)=当前日期(2020-04-01)-最小月份的1日(2019.2->2019-12-01)=4
  456. # def difMonth(dateStr):
  457. # return int(int(str(np.datetime64(time.strftime("%Y-%m-%d")) -
  458. # np.datetime64(dateStr.replace('.', '-'), "D")).split(" ")[0]) / 30);
  459. # 信贷交易明细汇总
  460. def parseLoanTradeInfo(dfObj):
  461. df = dfObj["df"];
  462. # row1 = df.loc[1, :]
  463. if not df.empty:
  464. loanMonthDf = df[1: 4]
  465. loanMonthDf = loanMonthDf.reset_index(drop=True)
  466. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '个人住房贷款账户数'] = utils.toInt(loanMonthDf.loc[0, :][2])
  467. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex,'个人商用房贷款(包括商住两用)账户数']=utils.toInt(loanMonthDf.loc[1, :][2])
  468. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '其他类贷款账户数'] = utils.toInt(loanMonthDf.loc[2, :][2])
  469. creditCardDf = df[4: 6];
  470. creditCardDf = creditCardDf.reset_index(drop=True)
  471. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '贷记卡账户数'] = utils.toInt(creditCardDf.loc[0, :][2])
  472. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '准贷记卡账户数'] = utils.toInt(creditCardDf.loc[1, :][2])
  473. # 解析呆账信息汇总
  474. def parseBadDebtsInfoSumDf(dfObj):
  475. df = dfObj["df"];
  476. if not df.empty:
  477. row1 = df.loc[2, :]
  478. briefInfoDf_badDebtsInfoSum.loc[badDebtsInfoIndex, '账户数'] = row1[0];
  479. briefInfoDf_badDebtsInfoSum.loc[badDebtsInfoIndex, '余额'] = utils.replaceAmt(row1[1]);
  480. # 解析被追偿信息汇总
  481. def parseRecoveryInfoSum(dfObj):
  482. df = dfObj["df"];
  483. if not df.empty:
  484. row1 = df.loc[2, :]
  485. row2 = df.loc[3, :]
  486. row3 = df.loc[4, :]
  487. overdueBrief["disposalInfoSumAccount"] = row1[1]; # 资产处置信息汇总笔数
  488. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '资产处置业务账户数'] = row1[1];
  489. overdueBrief["disposalInfoSumAmt"] = row1[2]; # 资产处置信息汇总余额
  490. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '资产处置业务余额'] = utils.replaceAmt(row1[2]);
  491. overdueBrief["advanceInfoSumAccount"] = row2[1]; # 垫款业务笔数
  492. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '垫款业务账户数'] = row2[1];
  493. overdueBrief["advanceInfoSumAmt"] = row2[2]; # 垫款业务余额
  494. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '垫款业务余额'] = utils.replaceAmt(row2[2]);
  495. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '合计总账户数'] = row3[1];
  496. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '合计总余额'] = utils.replaceAmt(row3[2]);
  497. # 贷款逾期账户数
  498. # 贷款逾期月份数
  499. # 贷款单月最高逾期总额
  500. # 贷款最长逾期月数
  501. def parseOverdueInfoSum(dfObj):
  502. df = dfObj["df"];
  503. if not df.empty:
  504. row2= df.loc[2, :]
  505. row3 = df.loc[3, :]
  506. row4 = df.loc[4, :]
  507. row5 = df.loc[5, :]
  508. row6 = df.loc[6, :]
  509. #这块的数据需要进行出来 TODO
  510. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '非循环贷帐户账户数'] = utils.toInt(row2[1]);
  511. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '非循环贷帐户月份数'] = utils.toInt(row2[2]);
  512. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '非循环贷帐户单月最高逾期总额'] = utils.replaceAmt(row2[3]);
  513. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '非循环贷帐户最长逾期月数'] = utils.toInt(row2[4]);
  514. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环额度下分账户账户数'] = utils.toInt(row3[1]);
  515. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环额度下分账户月份数'] = utils.toInt(row3[2]);
  516. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环额度下分账户单月最高逾期总额'] = utils.replaceAmt(row3[3]);
  517. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环额度下分账户最长逾期月数'] = utils.toInt(row3[4]);
  518. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环贷账户账户数'] = utils.toInt(row4[1]);
  519. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环贷账户月份数'] = utils.toInt(row4[2]);
  520. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环贷账户单月最高逾期总额'] = utils.replaceAmt(row4[3]);
  521. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环贷账户最长逾期月数'] = utils.toInt(row4[4]);
  522. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '贷记卡账户账户数'] = utils.toInt(row5[1]);
  523. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '贷记卡账户月份数'] = utils.toInt(row5[2]);
  524. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '贷记卡账户单月逾期总额'] = utils.replaceAmt(row5[3]);
  525. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '贷记卡账户最长逾期月数'] = utils.toInt(row5[4]);
  526. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '准贷记卡账户账户数'] = utils.toInt(row6[1]);
  527. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '准贷记卡账户月份数'] = utils.toInt(row6[2]);
  528. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '准贷记卡账户单月透支总额'] = utils.replaceAmt(row6[3]);
  529. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '准贷记卡账户最长透支月数'] = utils.toInt(row6[4]);
  530. overdueInfoAccountDf = df[df[1] != '--'];
  531. overdueInfoAccountDf = overdueInfoAccountDf[2:7]
  532. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '该用户所有逾期账户最长逾期/透支月数最大值']=np.max(overdueInfoAccountDf[4].astype('int'))
  533. #np.sum(overdueInfoAccountDf[1])
  534. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '该用户所有逾期账户数加总']= np.sum(overdueInfoAccountDf[1].astype('int'))# TODO
  535. # briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '该用户过去5年出现逾期的所有账户数目']=None# TODO
  536. # 未结清贷款法人机构数 从“未结清贷款信息汇总”中直接提取LoanLegalOrgNum
  537. # 未结清贷款机构数 从“未结清贷款信息汇总”中直接提取LoanOrgNum
  538. # 未结清贷款笔数 从“未结清贷款信息汇总”中直接提取CountNum
  539. # 未结清贷款合同总额 从“未结清贷款信息汇总”中直接提取ContractProfits
  540. # 未结清贷款合同余额 从“未结清贷款信息汇总”中直接提取Balance
  541. # 未结清贷款近6月平均应还款 从“未结清贷款信息汇总”中直接提取Last6MothsAvgRepayAmount
  542. # 个人贷款未结清笔数 "从“未结清贷款信息汇总”计算客户符合以下条件的贷款笔数
  543. # 1.贷款类型不为('%个人助学贷款%' ,'%农户贷款%')
  544. # 2.贷款额度>100元
  545. # 3.贷款状态不为“结清”"
  546. # 非循环贷账户信息汇总
  547. def doFilterCalc(dfx):
  548. dfx = dfx.replace('--', 0)
  549. return dfx;
  550. # 科学计数法转换
  551. def replaceAmt(dfx):
  552. return dfx.str.replace(',', '')
  553. # 非循环贷账户信息汇总
  554. def parseLoanAccountInfoSum(dfObj):
  555. df = dfObj["df"];
  556. if not df.empty:
  557. loanAccountInfoSumDf = df[2:3];
  558. loanAccountInfoSumDf = doFilterCalc(loanAccountInfoSumDf); # 替换--为0
  559. loanAccountInfoSumDf = loanAccountInfoSumDf.reset_index(drop=True)
  560. row0 = loanAccountInfoSumDf.loc[0,:]
  561. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户管理机构数'] = int(row0[0])
  562. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户账户数'] = int(row0[1])
  563. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户授信总额'] = int(utils.replaceAmt(row0[2]))
  564. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户余额'] = int(utils.replaceAmt(row0[3]))
  565. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户6月平均应还款'] = int(utils.replaceAmt(row0[4]))
  566. # 循环额度下分账户
  567. def parseCycleCreditAccountInfoSum(dfObj):
  568. df = dfObj["df"];
  569. if not df.empty:
  570. cycleCreditAccountInfoSumDf = df[2:3];
  571. cycleCreditAccountInfoSumDf = doFilterCalc(cycleCreditAccountInfoSumDf); # 替换--为0
  572. cycleCreditAccountInfoSumDf = cycleCreditAccountInfoSumDf.reset_index(drop=True)
  573. row0 = cycleCreditAccountInfoSumDf.loc[0,:]
  574. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户管理机构数'] = int(row0[0])
  575. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户账户数'] = int(row0[1])
  576. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户授信总额'] = int(utils.replaceAmt(row0[2]))
  577. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户余额'] = int(utils.replaceAmt(row0[3]))
  578. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户6月平均应还款'] = int(utils.replaceAmt(row0[4]))
  579. # 循环贷账户信息
  580. def parseCyleLoanAccountInfoSum(dfObj):
  581. df = dfObj["df"];
  582. if not df.empty:
  583. cycleLoanAccountInfoSumDf = df[2:3];
  584. cycleLoanAccountInfoSumDf = doFilterCalc(cycleLoanAccountInfoSumDf); # 替换--为0
  585. cycleLoanAccountInfoSumDf = cycleLoanAccountInfoSumDf.reset_index(drop=True)
  586. row0 = cycleLoanAccountInfoSumDf.loc[0,:]
  587. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户管理机构数'] = int(row0[0])
  588. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户账户数'] = int(row0[1])
  589. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户授信总额'] = int(utils.replaceAmt(row0[2]))
  590. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户余额'] = int(utils.replaceAmt(row0[3]))
  591. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户6月平均应还款'] = int(utils.replaceAmt(row0[4]))
  592. # 解析贷记卡信息汇总,包含准贷记卡
  593. def parseCreditCardInfoSum(dfObj):
  594. df = dfObj["df"];
  595. if not df.empty:
  596. creditCardInfoSumDf = df[2:3];
  597. creditCardInfoSumDf = doFilterCalc(creditCardInfoSumDf); # 替换--为0
  598. creditCardInfoSumDf = creditCardInfoSumDf.reset_index(drop=True)
  599. row0 = creditCardInfoSumDf.loc[0, :]
  600. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡发卡机构数'] = int(row0[0])
  601. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡账户数'] = int(row0[1])
  602. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡授信总额'] = int(utils.replaceAmt(row0[2]))
  603. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡单家机构最高授信额'] = int(utils.replaceAmt(row0[3]))
  604. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡单家机构最低授信额'] = int(utils.replaceAmt(row0[4]))
  605. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡已用额度'] = int(utils.replaceAmt(row0[5]))
  606. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡最近6个月平均使用额度'] = int(utils.replaceAmt(row0[6]))
  607. # 解析贷记卡信息汇总,包含准贷记卡
  608. def parseCreditCardInfoSumZ(dfObj):
  609. df = dfObj["df"];
  610. if not df.empty:
  611. creditCardInfoSumDfZ = df[2:3];
  612. creditCardInfoSumDfZ = doFilterCalc(creditCardInfoSumDfZ);
  613. creditCardInfoSumDfZ = creditCardInfoSumDfZ.reset_index(drop=True)
  614. row0 = creditCardInfoSumDfZ.loc[0, :]
  615. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡发卡机构数'] = int(row0[0])
  616. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡账户数'] = int(row0[1])
  617. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡授信总额'] = int(utils.replaceAmt(row0[2]))
  618. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡单家机构最高授信额'] = int(utils.replaceAmt(row0[3]))
  619. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡单家机构最低授信额'] = int(utils.replaceAmt(row0[4]))
  620. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡已用额度'] = int(utils.replaceAmt(row0[5]))
  621. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡最近6个月平均使用额度'] = int(utils.replaceAmt(row0[6]))
  622. #相关还款责任
  623. def parseRepaymentSum(dfObj):
  624. df = dfObj["df"];
  625. if not df.empty:
  626. row4 = df.loc[4,:].dropna().reset_index(drop=True)#第4行 为个人
  627. row8 = None
  628. if df.index.size ==9:
  629. row8 = df.loc[8,:].dropna().reset_index(drop=True)#第8行 为企业
  630. perAccountNum = 0;#个人账户数
  631. orgAccountNum = 0; # 企业账户数
  632. totalAccountNum = 0;#总账户数
  633. guaranteeAccountNum = 0;#相关还款责任总账户数-担保责任
  634. otherAccountNum =0;#相关还款责任总账户数-其他
  635. perGuaranteeAmt = 0#个人担保金额及其他
  636. orgGuaranteeAmt = 0#企业担保金额及其他
  637. totalGuaranteeAmt = 0;#总担保金额
  638. guaranteeAmt = 0;#相关还款责任总担保金额
  639. otherPaymentAmt = 0;#其他还款责任金额
  640. perGuaranteeBalance = 0 # 个人担保余额及其他
  641. orgGuaranteeBalance = 0 # 企业担保余额及其他
  642. totalGuaranteeBalance = 0;#总担保余额
  643. guaranteeBalance = 0;#相关还款责任总担保余额
  644. otherPaymentBalance = 0; # 其他还款责任余额
  645. #计算总账户数
  646. if row4[0] !="--":
  647. perAccountNum=perAccountNum+utils.toInt(row4[0])
  648. guaranteeAccountNum = guaranteeAccountNum + utils.toInt(row4[0])#个人担保责任账户数
  649. if row4[3] !="--":
  650. perAccountNum = perAccountNum + utils.toInt(row4[3])#其他
  651. otherAccountNum = otherAccountNum + utils.toInt(row4[3]) # 其他
  652. if row8 != None:
  653. if row8[0] != "--":
  654. orgAccountNum = orgAccountNum + utils.toInt(row8[0])
  655. guaranteeAccountNum = guaranteeAccountNum + utils.toInt(row8[0])#企业担保责任账户数
  656. if row8[3] != "--":
  657. orgAccountNum = orgAccountNum + utils.toInt(row8[3])#其他
  658. otherAccountNum = otherAccountNum + utils.toInt(row8[3]) # 其他
  659. totalAccountNum = perAccountNum+orgAccountNum
  660. #计算担保金额
  661. if row4[1] !="--":
  662. perGuaranteeAmt=perGuaranteeAmt+utils.replaceAmt(row4[1])#担保
  663. guaranteeAmt = guaranteeAmt + utils.replaceAmt(row4[1]) # 担保
  664. if row4[4] !="--":
  665. perGuaranteeAmt = perGuaranteeAmt + utils.replaceAmt(row4[4])#其他
  666. otherPaymentAmt = otherPaymentAmt + utils.replaceAmt(row4[4]) # 其他
  667. if row8 != None:
  668. if row8[1] != "--":
  669. orgGuaranteeAmt = orgGuaranteeAmt + utils.replaceAmt(row8[1])#担保
  670. guaranteeAmt = guaranteeAmt + utils.replaceAmt(row8[1]) # 担保
  671. if row8[4] != "--":
  672. orgGuaranteeAmt = orgGuaranteeAmt + utils.replaceAmt(row8[4])#其他
  673. otherPaymentAmt = otherPaymentAmt + utils.replaceAmt(row8[4]) # 其他
  674. totalGuaranteeAmt = perGuaranteeAmt + orgGuaranteeAmt
  675. # 计算余额
  676. if row4[2] !="--":
  677. perGuaranteeBalance=perGuaranteeBalance+utils.replaceAmt(row4[2])
  678. guaranteeBalance=guaranteeBalance+utils.replaceAmt(row4[2])#个人担保余额
  679. if row4[5] !="--":
  680. perGuaranteeBalance = perGuaranteeBalance + utils.replaceAmt(row4[5])#其他
  681. otherPaymentBalance = otherPaymentBalance + utils.replaceAmt(row4[5]) # 其他
  682. if row8 != None:
  683. if row8[2] != "--":
  684. orgGuaranteeBalance = orgGuaranteeBalance + utils.replaceAmt(row8[2])
  685. guaranteeBalance = guaranteeBalance + utils.replaceAmt(row8[2])#企业担保余额
  686. if row8[5] != "--":
  687. orgGuaranteeBalance = orgGuaranteeBalance + utils.replaceAmt(row8[5])
  688. otherPaymentBalance = otherPaymentBalance + utils.replaceAmt(row8[5]) # 其他
  689. totalGuaranteeBalance = perGuaranteeBalance + orgGuaranteeBalance
  690. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总账户数(担保+其他+个人+企业)'] =totalAccountNum
  691. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保金额+总还款责任金额(个人+企业)'] =totalGuaranteeAmt
  692. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任账户总担保余额+总其他余额(个人+企业)'] =totalGuaranteeBalance
  693. if totalGuaranteeAmt !=0:
  694. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任账户总担保余额+总其他余额(个人+企业)/相关还款责任账户总担保金额+总其他金额(个人+企业)'] =\
  695. round(totalGuaranteeBalance / totalGuaranteeAmt, 2)
  696. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任担保总账户数-个人'] =perAccountNum
  697. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保金额-个人'] =perGuaranteeAmt
  698. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-个人'] =perGuaranteeBalance
  699. if perGuaranteeBalance !=0:
  700. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-个人/相关还款责任总担保金额-个人'] = round(perGuaranteeBalance/perGuaranteeBalance,2)
  701. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总账户数-企业'] =orgAccountNum
  702. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保金额-企业'] =orgGuaranteeAmt
  703. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-企业'] =orgGuaranteeBalance
  704. if orgGuaranteeAmt!=0:
  705. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-企业/相关还款责任总担保金额-企业'] = round(orgGuaranteeBalance/orgGuaranteeAmt,2)
  706. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总账户数-担保责任'] =guaranteeAccountNum
  707. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保金额-担保责任'] =guaranteeAmt
  708. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任账户总担保余额-担保责任'] =guaranteeBalance
  709. if guaranteeAmt!=0:
  710. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-担保责任/相关还款责任总担保金额-担保责任'] =round(guaranteeBalance/guaranteeAmt,2)
  711. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总账户数-其他'] =otherAccountNum
  712. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保金额-其他'] =otherPaymentAmt
  713. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-其他'] =otherPaymentBalance
  714. if otherPaymentAmt!=0:
  715. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任账户总担保余额-其他/相关还款责任账户总担保金额-其他'] =round(otherPaymentBalance/otherPaymentAmt,2)
  716. #解析公共信息汇总
  717. def parsePublicInfoBrief(dfObj):
  718. df = dfObj["df"];
  719. if not df.empty:
  720. publicInfoBrief = df[1:6];
  721. publicInfoBrief = publicInfoBrief.reset_index(drop=True)
  722. row0 = publicInfoBrief.loc[0, :]
  723. row1 = publicInfoBrief.loc[1, :]
  724. row2 = publicInfoBrief.loc[2, :]
  725. row3 = publicInfoBrief.loc[3, :]
  726. publicInfoBriefDf.loc[publicInfoBriefIndex, '欠税信息-记录数'] = int(row0[1])
  727. publicInfoBriefDf.loc[publicInfoBriefIndex, '欠税信息-涉及金额'] = int(utils.replaceAmt(row0[2]))
  728. publicInfoBriefDf.loc[publicInfoBriefIndex, '民事判决信息-记录数'] = int(row1[1])
  729. publicInfoBriefDf.loc[publicInfoBriefIndex, '民事判决信息-涉及金额'] = int(utils.replaceAmt(row1[2]))
  730. publicInfoBriefDf.loc[publicInfoBriefIndex, '强制执行信息-记录数'] = int(row2[1])
  731. publicInfoBriefDf.loc[publicInfoBriefIndex, '强制执行信息-涉及金额'] = int(utils.replaceAmt(row2[2]))
  732. publicInfoBriefDf.loc[publicInfoBriefIndex, '行政处罚信息-记录数'] = int(row3[1])
  733. publicInfoBriefDf.loc[publicInfoBriefIndex, '行政处罚信息-涉及金额'] = int(utils.replaceAmt(row3[2]))
  734. #解析查询信息汇总
  735. def parseQueryRecordSum(dfObj):
  736. df = dfObj["df"];
  737. if not df.empty:
  738. queryRecordSumDfTmp = df[2:3];
  739. queryRecordSumDfTmp = queryRecordSumDfTmp.reset_index(drop=True)
  740. row0 = queryRecordSumDfTmp.loc[0, :]
  741. queryRecordSumDf.loc[queryRecordSumIndex, '近1月内的查询机构数-贷款审批'] =int(row0[0])
  742. queryRecordSumDf.loc[queryRecordSumIndex, '近1月内的查询机构数-信用卡审批'] =int(row0[1])
  743. queryRecordSumDf.loc[queryRecordSumIndex, '近1月内的查询次数-贷款审批'] =int(row0[2])
  744. queryRecordSumDf.loc[queryRecordSumIndex, '近1月内的查询次数-信用卡审批'] =int(row0[3])
  745. queryRecordSumDf.loc[queryRecordSumIndex, '近1月内的查询次数-本人查询'] =int(row0[4])
  746. queryRecordSumDf.loc[queryRecordSumIndex, '近2年内的查询次数-贷后管理'] =int(row0[5])
  747. queryRecordSumDf.loc[queryRecordSumIndex, '近2年内的查询次数-担保资格审查'] =int(row0[6])
  748. # 解析查询记录明细
  749. def parseQueryInfoDetail(dfObj):
  750. df = dfObj["df"];
  751. reportTime = queryInfo["reportTime"];
  752. if not df.empty:
  753. df = utils.replaceDateCol(df)
  754. df = df[1:df.index.size] # 去掉表头
  755. queryRecordDetailDf.loc[queryRecordDetailIndex, '近1月查询次数'] =qip.getLastMonthQueryTimes(df, 1, "",reportTime)
  756. queryRecordDetailDf.loc[queryRecordDetailIndex, '近3月查询次数'] =qip.getLastMonthQueryTimes(df, 3, "",reportTime)
  757. queryRecordDetailDf.loc[queryRecordDetailIndex, '近6月查询次数'] =qip.getLastMonthQueryTimes(df, 6, "",reportTime)
  758. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12月查询次数'] =qip.getLastMonthQueryTimes(df, 12, "",reportTime)
  759. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近1个月查询机构数'] =qip.getLastMonthQueryOrgTimes(df, 1, "", reportTime)
  760. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近3个月查询机构数'] =qip.getLastMonthQueryOrgTimes(df, 3, "", reportTime)
  761. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近6个月查询机构数'] =qip.getLastMonthQueryOrgTimes(df, 6, "", reportTime)
  762. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近12个月查询机构数'] =qip.getLastMonthQueryOrgTimes(df, 12, "", reportTime)
  763. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近24个月查询机构数'] =qip.getLastMonthQueryOrgTimes(df, 24, "", reportTime)
  764. queryRecordDetailDf.loc[queryRecordDetailIndex, '近3月查询次数贷款审批'] =qip.getLastMonthQueryTimes(df, 3, consts.loanApprove, reportTime)
  765. queryRecordDetailDf.loc[queryRecordDetailIndex, '近3月查询次数信用卡审批'] =qip.getLastMonthQueryTimes(df, 3, consts.creditCard, reportTime)
  766. queryRecordDetailDf.loc[queryRecordDetailIndex, '近6月查询次数贷款审批'] =qip.getLastMonthQueryTimes(df, 6, consts.loanApprove, reportTime)
  767. queryRecordDetailDf.loc[queryRecordDetailIndex, '近6月查询次数信用卡审批'] = qip.getLastMonthQueryTimes(df, 6, consts.creditCard, reportTime)
  768. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12月查询次数贷款审批'] = qip.getLastMonthQueryTimes(df, 12, consts.loanApprove, reportTime)
  769. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12月查询次数信用卡审批'] =qip.getLastMonthQueryTimes(df, 12, consts.creditCard, reportTime)
  770. queryRecordDetailDf.loc[queryRecordDetailIndex, '近3月查询机构数贷款审批'] =qip.getLastMonthQueryOrgTimes(df, 3, consts.loanApprove, reportTime)
  771. queryRecordDetailDf.loc[queryRecordDetailIndex, '近3月查询机构数信用卡审批'] =qip.getLastMonthQueryOrgTimes(df, 3, consts.creditCard, reportTime)
  772. queryRecordDetailDf.loc[queryRecordDetailIndex, '近6月查询机构数贷款审批'] =qip.getLastMonthQueryOrgTimes(df, 6, consts.loanApprove, reportTime)
  773. queryRecordDetailDf.loc[queryRecordDetailIndex, '近6月查询机构数信用卡审批'] = qip.getLastMonthQueryOrgTimes(df, 6, consts.creditCard,reportTime)
  774. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12月查询机构数贷款审批'] = qip.getLastMonthQueryOrgTimes(df, 12, consts.loanApprove, reportTime)
  775. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12月查询机构数信用卡审批'] = qip.getLastMonthQueryOrgTimes(df, 12, consts.creditCard,reportTime)
  776. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近6个月担保资格审查查询次数'] = qip.getLastMonthQueryOrgTimes(df, 6, consts.insuranceAprove,reportTime)
  777. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12个月担保资格审查查询次数'] = qip.getLastMonthQueryOrgTimes(df, 12, consts.insuranceAprove,reportTime)
  778. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近6个月贷后管理查询次数'] = qip.getLastMonthQueryOrgTimes(df, 6, consts.loanAfterMgr,reportTime)
  779. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近12个月贷后管理查询次数'] = qip.getLastMonthQueryOrgTimes(df, 12, consts.loanAfterMgr,reportTime)
  780. queryRecordDetailDf.loc[queryRecordDetailIndex, '最后一次查询距离现在的月数贷款审批'] = qip.getLastTimeQueryMonth(df, consts.loanApprove,reportTime)
  781. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近24个月贷后管理查询次数'] = qip.getLastMonthQueryTimes(df, 24, consts.loanAfterMgr, reportTime)
  782. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近24个月贷款审批审批次数'] = qip.getLastMonthQueryTimes(df, 24, consts.loanApprove, reportTime)
  783. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近24个月信用卡审批查询次数'] = qip.getLastMonthQueryTimes(df, 24, consts.creditCard,reportTime)
  784. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近24个月担保资格审查查询次数'] = qip.getLastMonthQueryTimes(df, 24, consts.insuranceAprove,reportTime)
  785. #解析住房公积金
  786. def parseHousingFundRcd(df):
  787. if not df.empty:
  788. lastHousingFundRcdDf = df.sort_values(by=["信息更新日期"] , ascending=(False)).reset_index(drop=True)
  789. lastHousingFundRcdDf = lastHousingFundRcdDf[0:1]#最新
  790. row1 = lastHousingFundRcdDf.loc[0,:].dropna().reset_index(drop=True)
  791. housingFundRcdDf.loc[housingFundRcdIndex, '参缴地'] =row1[1]
  792. housingFundRcdDf.loc[housingFundRcdIndex, '参缴日期'] =row1[2]
  793. housingFundRcdDf.loc[housingFundRcdIndex, '初缴月份'] =row1[3]#初缴日期
  794. housingFundRcdDf.loc[housingFundRcdIndex, '缴至月份'] =row1[4]
  795. housingFundRcdDf.loc[housingFundRcdIndex, '缴费状态'] =row1[5]
  796. housingFundRcdDf.loc[housingFundRcdIndex, '月缴存额'] =row1[6]
  797. housingFundRcdDf.loc[housingFundRcdIndex, '个人存缴比例'] =row1[7]
  798. housingFundRcdDf.loc[housingFundRcdIndex, '单位存缴比例'] =row1[8]
  799. housingFundRcdDf.loc[housingFundRcdIndex, '缴费单位'] =row1[9]#扣缴单位
  800. housingFundRcdDf.loc[housingFundRcdIndex, '信息更新日期'] =row1[10]
  801. reportTime = queryInfo["reportTime"];
  802. lastDateStr = utils.getLastMonthDate(reportTime,12)
  803. avgHousingFundDf = df[df['缴至月份']>=lastDateStr]
  804. housingFundRcdDf.loc[housingFundRcdIndex, '最近1年公积金平均值'] = round(np.mean(avgHousingFundDf['月缴存额']),2)
  805. lastDateStr = utils.getLastMonthDate(reportTime, 12*3)
  806. avgHousingFundDf = df[df['缴至月份'] >= lastDateStr]
  807. housingFundRcdDf.loc[housingFundRcdIndex, '最近3年公积金平均值']= round(np.mean(avgHousingFundDf['月缴存额']),2)
  808. #解析贷款还款记录指标
  809. def parseLoanMergeAndPayRecordDf(df,payRcdDf):
  810. if not df.empty and not payRcdDf.empty:
  811. #正常
  812. normalDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['账户状态'] != '呆账')]
  813. overduePayRcdDf = payRcdDf[payRcdDf['账户编号'].isin(normalDf['账户编号'].values)]
  814. overduePayRcdDf = utils.replacePayRcdStatus(overduePayRcdDf)
  815. #计算当前贷款,为还款记录的最后一期 0529
  816. curOverduePayRcdDf=overduePayRcdDf.sort_values(by=["账户编号", "还款日期"], ascending=(True, False))
  817. curOverduePayRcdDf = curOverduePayRcdDf.groupby(['账户编号']).head(1)
  818. curOverduePayRcdDf = curOverduePayRcdDf[curOverduePayRcdDf['还款状态'] > 0]
  819. #临时保存,不用过滤还款状态为0的
  820. payRcdMaxOverdueDf = overduePayRcdDf;
  821. #所有逾期的记录
  822. # overduePayRcdDf = overduePayRcdDf[overduePayRcdDf['还款状态']>0]
  823. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期账户数'] = curOverduePayRcdDf['账户编号'].unique().size
  824. if normalDf.index.size>0:
  825. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期账户数占比'] = round(loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期账户数']/normalDf.index.size,3)
  826. #存在逾期的贷款账户 非结清的过滤出逾期的账户号
  827. overdueLoanDf = normalDf[normalDf['账户编号'].isin(curOverduePayRcdDf['账户编号'].values)]
  828. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期机构数'] = overdueLoanDf['管理机构'].unique().size
  829. if normalDf['管理机构'].unique().size>0:
  830. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期机构数占比'] = round(loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期机构数'] / normalDf['管理机构'].unique().size,2)
  831. #还款记录按日期排序最近3笔的最大逾期期数
  832. loanAccountInfoDf.loc[loanAccountInfoIndex, '近1月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf,1);
  833. loanAccountInfoDf.loc[loanAccountInfoIndex, '近3月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 3);
  834. loanAccountInfoDf.loc[loanAccountInfoIndex, '近6月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 6);
  835. loanAccountInfoDf.loc[loanAccountInfoIndex, '近9月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 9);
  836. loanAccountInfoDf.loc[loanAccountInfoIndex, '近24月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 24);
  837. reportTime = queryInfo["reportTime"]
  838. loanAccountInfoDf.loc[loanAccountInfoIndex, '近24月贷款最大逾期距离现在的月数'] = prp.getPayRcdMaxOverdueNumMonth(payRcdMaxOverdueDf,normalDf,reportTime, 24);
  839. payStatus= ["G","D","C","N","M","1","2","3","4","5","6","7"]
  840. # 贷款24期还款记录次数 剔除结清 转出 呆账
  841. payRcdTimesDf = payRcdDf[payRcdDf['账户编号'].isin(normalDf['账户编号'].values)]
  842. payRcdTimesDf = payRcdTimesDf.sort_values(by=["账户编号", "还款日期"], ascending=(True, False))
  843. payRcdTimesDf = payRcdTimesDf.groupby(['账户编号']).head(24)
  844. #从“贷款信息”中提取,剔除“账户状态”为结清、转出、呆账、呆帐后,各账户的还款次数统计“24个月(账户)还款状态”包含"G","D","C","N","M"及数字的个数,MAX(各账户的还款次数)
  845. payRcdTimesDf = payRcdTimesDf[payRcdTimesDf['还款状态'].isin(payStatus)]
  846. payRcdTimes = payRcdTimesDf.groupby(['账户编号'])['还款状态'].count()
  847. loanAccountInfoDf.loc[loanAccountInfoIndex, '贷款24期还款记录次数'] = np.max(payRcdTimes)
  848. #解析信贷交易明细-特殊交易
  849. def parseSpecialTrade(df):
  850. if not df.empty:
  851. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '当前用户发生特殊交易的严重程度'] = np.max(df['严重程度'])#加工的指标
  852. maxChangeMonthIndex = np.argmax(np.abs(df['变更月数']))
  853. meanMonthValue = np.mean(np.abs(df['变更月数']))
  854. row0 = df.loc[maxChangeMonthIndex, :]
  855. settleDf = df[(df['特殊交易类型']=='提前结清') | (df['特殊交易类型']=='提前还款')]
  856. debtDf = df[(df['特殊交易类型'] == '以资抵债')]
  857. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户发生特殊交易变更月数的最大差值'] = row0[3]
  858. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户发生特殊交易变更月数的平均差值'] = round(meanMonthValue,2)
  859. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户特殊交易涉及的发生金额的最大值'] = np.max(df['发生金额'])
  860. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户特殊交易涉及的发生金额的平均值'] = round(np.mean(df['发生金额']),2)
  861. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户所有帐户发生提前还款交易的次数统计'] = settleDf.index.size
  862. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户所有帐户发生不良特殊交易的次数统计'] = debtDf.index.size;
  863. #信贷交易明细-非循环贷账户
  864. def parseLoanAccountInfo(df):
  865. if not df.empty:
  866. loanAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户账户数'])
  867. normalDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['账户状态'] != '呆账')].reset_index(drop=True)
  868. normalDf = normalDf[0:loanAccountNum]#根据非循环贷账户数进行计算进行截取
  869. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '本月应还款(合计)'] = np.sum(normalDf['本月应还款'])
  870. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '本月实还款(合计)'] = np.sum(normalDf['本月实还款'])
  871. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '最近一次还款日期'] = np.max(normalDf['最近一次还款日期'])
  872. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '当前一共逾期期数'] = np.sum(normalDf['当前逾期期数'])
  873. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '当前一共逾期总额'] = np.sum(normalDf['当前逾期总额'])
  874. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '逾期31-60天未还本金(合计)'] = np.sum(normalDf['逾期31-60天未还本金'])
  875. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '逾期61-90天未还本金(合计)'] = np.sum(normalDf['逾期61-90天未还本金'])
  876. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '逾期91-180天未还本金(合计)'] = np.sum(normalDf['逾期91-180天未还本金'])
  877. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '逾期180天以上未还本金(合计)']= np.sum(normalDf['逾期180天以上未还本金'])
  878. #信贷交易明细-循环额度分账户
  879. def parseCycleCreditAccountInfo(df):
  880. if not df.empty:
  881. normalDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['账户状态'] != '呆账')].reset_index(drop=True)
  882. loanAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户账户数'])
  883. cycleCreditAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户账户数'])
  884. normalDf = normalDf[loanAccountNum:(loanAccountNum + cycleCreditAccountNum)]
  885. if not normalDf.empty:
  886. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '本月应还款(合计)'] = np.sum(normalDf['本月应还款'])
  887. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '本月实还款(合计)'] = np.sum(normalDf['本月实还款'])
  888. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '最近一次还款日期'] = np.max(normalDf['最近一次还款日期'])
  889. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '当前一共逾期期数'] = np.sum(normalDf['当前逾期期数'])
  890. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '当前一共逾期总额'] = np.sum(normalDf['当前逾期总额'])
  891. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '逾期31-60天未还本金(合计)'] = np.sum(normalDf['逾期31-60天未还本金'])
  892. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '逾期61-90天未还本金(合计)'] = np.sum(normalDf['逾期61-90天未还本金'])
  893. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '逾期91-180天未还本金(合计)'] = np.sum(normalDf['逾期91-180天未还本金'])
  894. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '逾期180天以上未还本金(合计)']= np.sum(normalDf['逾期180天以上未还本金'])
  895. #信贷交易明细-循环贷账户
  896. def parseCycleLoanAccountInfo(df):
  897. if not df.empty:
  898. normalDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['账户状态'] != '呆账')]
  899. loanAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户账户数'])
  900. cycleCreditAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户账户数'])
  901. cycleAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户账户数'])
  902. normalDf = normalDf[(loanAccountNum+cycleCreditAccountNum):normalDf.index.size]
  903. if not normalDf.empty:
  904. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '本月应还款(合计)'] = np.sum(normalDf['本月应还款'])
  905. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '本月实还款(合计)'] = np.sum(normalDf['本月实还款'])
  906. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '最近一次还款日期'] = np.max(normalDf['最近一次还款日期'])
  907. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '当前一共逾期期数'] = np.sum(normalDf['当前逾期期数'])
  908. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '当前一共逾期总额'] = np.sum(normalDf['当前逾期总额'])
  909. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '逾期31-60天未还本金(合计)'] = np.sum(normalDf['逾期31-60天未还本金'])
  910. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '逾期61-90天未还本金(合计)'] = np.sum(normalDf['逾期61-90天未还本金'])
  911. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '逾期91-180天未还本金(合计)'] = np.sum(normalDf['逾期91-180天未还本金'])
  912. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '逾期180天以上未还本金(合计)']= np.sum(normalDf['逾期180天以上未还本金'])
  913. #解析贷款账户信息指标
  914. def parseLoanMergeDf(df):
  915. if not df.empty:
  916. sortDf = df.sort_values(by=["账户关闭日期","借款金额(本金)"] , ascending=(False,False))
  917. sortDf = sortDf[sortDf['账户状态'] == '结清'];
  918. sortDf = sortDf.reset_index(drop=True)
  919. if not sortDf.empty:
  920. row0 = sortDf.loc[0, :]
  921. loanAccountInfo["lastSettleLoanAmt"] = row0['借款金额(本金)']
  922. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近一笔结清贷款的贷款金额'] = row0['借款金额(本金)']
  923. openDate = dfParser.formatDate(row0['开立日期'])
  924. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近一笔结清贷款的发放距今月数'] = utils.difMonthReportTime(openDate,queryInfo["reportTime"])
  925. settleDate = dfParser.formatDate(row0['账户关闭日期'])
  926. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近一笔结清贷款的结清距今月数'] = utils.difMonthReportTime(settleDate,queryInfo["reportTime"])
  927. loanAccountInfoDf.loc[loanAccountInfoIndex, '历史贷款总法人机构数'] = df['管理机构'].unique().size
  928. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前同时在用的贷款机构数'] = df[df['余额(本金)']>0]['管理机构'].unique().size
  929. statusDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出')]
  930. bankDf = statusDf[statusDf['管理机构'].str.contains('银行')]
  931. #没有记录
  932. if statusDf.index.size==0:
  933. isNotBankCust = -1
  934. else:
  935. if bankDf.index.size >0:#有一条以上不为结清,请包含银行
  936. isNotBankCust = 1;
  937. else:
  938. isNotBankCust = 0;
  939. loanAccountInfoDf.loc[loanAccountInfoIndex, '是否有非银行贷款客户'] = isNotBankCust
  940. #最严重的五级分类
  941. # fiveType = ""
  942. # for fiveTypeTmp in consts.fiveType:
  943. # fiveTypeDf = statusDf[statusDf['五级分类']==fiveTypeTmp];
  944. # if not fiveTypeDf.empty:
  945. # fiveType = fiveTypeTmp;
  946. # break;
  947. # loanAccountInfoDf.loc[loanAccountInfoIndex, '贷款五级分类'] = fiveType
  948. #当前贷款LTV
  949. # 从“贷款信息”中提取,剔除“账户状态”为结清及转出,并剔除“账户状态”为呆账且本金余额 = 0
  950. # 的记录后,SUM(本金余额) / SUM(贷款本金)
  951. # 如本金余额为空和贷款本金为0或为空,则当条记录不计算
  952. loanLtvDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['借款金额(本金)']>0) & (df['余额(本金)']!='--')]
  953. badSetDf = loanLtvDf[~((loanLtvDf['账户状态'] == '呆账') & (loanLtvDf['余额(本金)']==0))]
  954. balanceSum = np.sum(badSetDf['余额(本金)'].astype('int'))
  955. loanAmtSum = np.sum(badSetDf['借款金额(本金)'].astype('int'))
  956. if(loanAmtSum !=0):
  957. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款LTV'] = round(np.divide(balanceSum,loanAmtSum),2)
  958. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款最高LTV'] = round(np.max(np.divide(badSetDf['余额(本金)'].astype('int'), badSetDf['借款金额(本金)'].astype('int'))),2)
  959. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款最低LTV'] = round(np.min(np.divide(badSetDf['余额(本金)'].astype('int'), badSetDf['借款金额(本金)'].astype('int'))), 2)
  960. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款平均LTV'] = round(np.mean(np.divide(badSetDf['余额(本金)'].astype('int'), badSetDf['借款金额(本金)'].astype('int'))), 2)
  961. #['个人住房商业贷款','个人商用房(含商住两用)贷款','个人住房公积金贷款','房'],
  962. houseLtvList = consts.houseLtvList;
  963. # houseLtvDf = badSetDf[badSetDf['业务种类'].isin(houseLtvList)]
  964. # if not houseLtvDf.empty:
  965. # loanAccountInfoDf.loc[loanAccountInfoIndex, '当前房贷LTV'] = round(np.divide(np.sum(houseLtvDf['余额(本金)'].astype('int')),np.sum(houseLtvDf['借款金额(本金)'].astype('int'))), 2)
  966. #['个人住房贷款','个人商用房(包括商住两用)贷款']
  967. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前房贷LTV'] = lip.getCurLtv(badSetDf, houseLtvList)
  968. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款机构数量'] = loanLtvDf['管理机构'].unique().size
  969. cardLtvList = ['个人汽车消费贷款','车']
  970. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前车贷LTV'] = lip.getCurLtv(badSetDf, cardLtvList)
  971. operateLtvList = ['个人经营性贷款']
  972. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前经营贷LTV'] = lip.getCurLtv(badSetDf, operateLtvList)
  973. consumeLtvList = ['其他个人消费贷款']
  974. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前消费贷LTV'] = lip.getCurLtv(badSetDf, consumeLtvList)
  975. bankLtvList = ['商业银行','外资银行','村镇银行','住房储蓄银行','财务公司']
  976. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前银行贷LTV'] = lip.getCurBankLtv(badSetDf, bankLtvList)
  977. bankLtvList = ['消费金融公司','汽车金融公司','信托公司']# TODO
  978. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前消金贷LTV'] = lip.getCurBankLtv(badSetDf, bankLtvList)
  979. smallLoanLtvList = ['小额信贷公司']
  980. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前小贷LTV'] = lip.getCurBankLtv(badSetDf, smallLoanLtvList)
  981. #当前贷款最大逾期期数
  982. # 从“贷款信息”中提取,剔除“账户状态”为结清、转出、呆账、呆帐后,MAX(每笔贷款的当前逾期期数)
  983. loanOverdueLtvDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['账户状态'] != '呆账')]
  984. if not loanOverdueLtvDf.empty:
  985. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款最大逾期期数'] = np.max(loanOverdueLtvDf['当前逾期期数'])
  986. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款最大逾期金额'] = np.max(loanOverdueLtvDf['当前逾期总额'])
  987. loanOverdueLtvDf=loanOverdueLtvDf.reset_index(drop=True)
  988. maxOverdueIndex = np.argmax(loanOverdueLtvDf['当前逾期期数'])
  989. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款最大逾期期数对应的最大逾期金额'] = loanOverdueLtvDf.loc[maxOverdueIndex,:]['当前逾期总额']
  990. loanAccountInfoDf.loc[loanAccountInfoIndex, '近3月开户最高贷款本金'] = lip.getLastLoanAmtMax(df,queryInfo["reportTime"],3)#贷款指标加工单独放到一个文件里
  991. loanAccountInfoDf.loc[loanAccountInfoIndex, '近3月开户最低贷款本金'] = lip.getLastLoanAmtMin(df, queryInfo["reportTime"], 3)
  992. loanAccountInfoDf.loc[loanAccountInfoIndex, '近3月开户平均贷款本金'] = lip.getLastLoanAmtAvg(df, queryInfo["reportTime"], 3)
  993. loanAccountInfoDf.loc[loanAccountInfoIndex, '近6月开户最高贷款本金'] = lip.getLastLoanAmtMax(df, queryInfo["reportTime"], 6)
  994. loanAccountInfoDf.loc[loanAccountInfoIndex, '近6月开户最低贷款本金'] = lip.getLastLoanAmtMin(df, queryInfo["reportTime"], 6)
  995. loanAccountInfoDf.loc[loanAccountInfoIndex, '近6月开户平均贷款本金'] = lip.getLastLoanAmtAvg(df, queryInfo["reportTime"], 6)
  996. loanAccountInfoDf.loc[loanAccountInfoIndex, '近12月开户最高贷款本金'] = lip.getLastLoanAmtMax(df, queryInfo["reportTime"], 12)
  997. loanAccountInfoDf.loc[loanAccountInfoIndex, '近12月开户最低贷款本金'] = lip.getLastLoanAmtMin(df, queryInfo["reportTime"], 12)
  998. loanAccountInfoDf.loc[loanAccountInfoIndex, '近12月开户平均贷款本金'] = lip.getLastLoanAmtAvg(df, queryInfo["reportTime"], 12)
  999. lastLoanDf = loanOverdueLtvDf;
  1000. if not lastLoanDf.empty:
  1001. loanAccountInfoDf.loc[loanAccountInfoIndex, '贷款最近一次还款日期距今时长'] = lip.getLastPayDateMinDays(lastLoanDf,queryInfo["reportTime"])
  1002. normalDf = df[(df['账户状态'] == '正常') & (df['当前逾期期数'] == 0)]
  1003. #未结清贷款总账户数:账户状态不等于结清和转出的记录数
  1004. notSettleDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出')]
  1005. if not notSettleDf.empty:
  1006. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常贷款账户数'] = normalDf.index.size
  1007. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常贷款账户数占比'] = round(normalDf.index.size/notSettleDf.index.size,2)
  1008. #当前未结清贷款余额总和
  1009. # ltvDf = tmpDf[tmpDf['业务种类'].isin(bizTypeList)]
  1010. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前未结清贷款余额总和'] = np.sum(notSettleDf['余额(本金)'])
  1011. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前未结清贷款余额总和'] = np.sum(notSettleDf['余额(本金)'])
  1012. # 当前未结清住房贷款余额总和
  1013. houseDf = notSettleDf[notSettleDf['业务种类'].isin(houseLtvList)]
  1014. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前未结清住房贷款余额总和'] = np.sum(houseDf['余额(本金)'])
  1015. # 当前未结清汽车贷款余额总和
  1016. cardDf = notSettleDf[notSettleDf['业务种类'].isin(cardLtvList)]
  1017. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前未结清汽车贷款余额总和'] = np.sum(cardDf['余额(本金)'])
  1018. # 当前未结清个人经营性贷款余额总和
  1019. operateLtvDf = notSettleDf[notSettleDf['业务种类'].isin(operateLtvList)]
  1020. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前未结清个人经营性贷款余额总和'] = np.sum(operateLtvDf['余额(本金)'])
  1021. # 当前平均每月贷款余额总和
  1022. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前平均每月贷款余额总和'] = round(np.sum(notSettleDf['余额(本金)'])/12,2)
  1023. #当前正常贷款账户余额
  1024. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常贷款账户余额'] = np.sum(normalDf['余额(本金)'])
  1025. # "从“贷款信息”中提取,剔除结清、转出,当前正常贷款账户余额/未结清贷款总余额(本金余额加总)
  1026. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常贷款账户余额占总余额比'] = round(np.sum(normalDf['余额(本金)'])/np.sum(notSettleDf['余额(本金)']),2)
  1027. settleDf = df[(df['账户状态'] == '结清')]
  1028. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常结清贷款账户数'] = settleDf.index.size
  1029. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常结清贷款账户数占比'] = round(settleDf.index.size/df.index.size,2)
  1030. #贷款24期还款记录次数 TODO
  1031. # 最近3个月个人消费贷款发放额度
  1032. loanAccountInfoDf.loc[loanAccountInfoIndex, '贷款本月实还款金额'] = np.sum(loanOverdueLtvDf['本月应还款'])
  1033. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近3个月个人消费贷款发放额度'] = lip.getLastPerConsumeAmt(df,3,queryInfo["reportTime"])
  1034. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近6个月个人消费贷款发放额度'] = lip.getLastPerConsumeAmt(df, 6,queryInfo["reportTime"])
  1035. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近12个月个人消费贷款发放额度'] = lip.getLastPerConsumeAmt(df, 12,queryInfo["reportTime"])
  1036. #未结清贷款平均剩余还款期数
  1037. payPieDf = notSettleDf[notSettleDf['还款期数']!='--']
  1038. if payPieDf.index.size!=0:
  1039. loanAccountInfoDf.loc[loanAccountInfoIndex, '未结清贷款平均剩余还款期数'] = round(np.sum(payPieDf['剩余还款期数'])/payPieDf.index.size,2)
  1040. # 当前贷款本月应还金额总和
  1041. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款本月应还金额总和'] = np.sum(notSettleDf['本月应还款'])
  1042. # 当前贷款本月实还金额总额
  1043. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款本月实还金额总额'] = np.sum(notSettleDf['本月实还款'])
  1044. #解析贷记卡账户信息指标
  1045. def parseCreditCardMergeDf(df):
  1046. if not df.empty:
  1047. # 历史信用卡总法人机构数
  1048. # creditCardAccountInfoDf.loc[creditCardAccountInfoIndex,'历史信用卡总法人机构数'] = df['发卡机构'].unique().size
  1049. # creditCardUseDf = df[df['已用额度']>0];
  1050. # creditCardAccountInfoDf.loc[creditCardAccountInfoIndex,'当前同时在用的信用卡机构数'] = creditCardUseDf['发卡机构'].unique().size
  1051. #统一排除
  1052. creditDf = df[(df['币种'] == '人民币元') & (df['账户状态'] != '未激活') & (df['账户状态'] != '销户') & (df['账户状态'] != '呆账')]
  1053. totalAmtDf = df[(df['币种'] == '人民币元') & (df['账户状态'] != '未激活') & (df['账户状态'] != '销户') & (df['账户状态'] != '呆账')]
  1054. #大额专项分期额度(合计)
  1055. # 已用分期金额(合计)
  1056. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '大额专项分期额度(合计)'] = np.sum(creditDf['大额专项分期额度'])
  1057. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '已用分期金额(合计)'] = np.sum(creditDf['已用分期金额'])
  1058. # creditCardAccountInfoDf.loc[creditCardAccountInfoIndex,'贷记卡账户当前总额度'] = cip.getMaxCreditAmt(creditDf)
  1059. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近新发放的3张贷记卡平均额度'] = cip.getAvgCreditAmt(creditDf)
  1060. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡额度使用率超过90%的机构数占比'] = cip.getUseRate(creditDf,df,0.9)
  1061. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡额度使用率超过100%的机构数占比'] = cip.getUseRate(creditDf, totalAmtDf, 1)
  1062. # 从“贷记卡信息”中提取,计算授信额度时剔除销户,计算已用额度时剔除呆账、呆帐、销户后,SUM(各账户已用额度) / SUM(各账户授信额度)
  1063. useCreditDf = df[(df['币种'] == '人民币元') & (df['账户状态'] != '销户') & (df['账户状态'] != '呆账')]
  1064. totalCreditDf = df[(df['币种'] == '人民币元') & (df['账户状态'] != '销户')]
  1065. totalCreditAmt = np.sum(totalCreditDf['账户授信额度'])
  1066. if totalCreditAmt != 0:#授信额度不能为0
  1067. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡账户当前总额度使用率'] = round(np.sum(useCreditDf['已用额度'])/np.sum(totalCreditDf['账户授信额度']),2)
  1068. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡账户最高使用额度总的使用率'] = round(np.sum(useCreditDf['最大使用额']) / np.sum(totalCreditDf['账户授信额度']), 2)
  1069. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡账户近6月平均额度总的使用率'] = round(np.sum(useCreditDf['最近6个月平均使用额度']) / np.sum(totalCreditDf['账户授信额度']), 2)
  1070. # creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡最大逾期期数'] = np.max(creditDf['当前逾期期数'])#用于计算
  1071. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡最大逾期金额'] = np.max(creditDf['当前逾期总额'])
  1072. if not creditDf.empty:
  1073. creditDf = creditDf.reset_index(drop=True)
  1074. maxOverdueIndex = np.argmax(creditDf['当前逾期期数'])
  1075. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡最大逾期期数对应的最大逾期金额'] = creditDf.loc[maxOverdueIndex,:]['当前逾期总额']
  1076. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近3月开卡最高额度'] = cip.getLastMonthMaxCreditAmt(df,queryInfo["reportTime"],3)
  1077. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近3月开卡最低额度'] = cip.getLastMonthMinCreditAmt(df, queryInfo["reportTime"], 3)
  1078. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近3月开卡平均额度'] = cip.getLastMonthAvgCreditAmt(df, queryInfo["reportTime"], 3)
  1079. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近6月开卡最高额度'] = cip.getLastMonthMaxCreditAmt(df, queryInfo["reportTime"], 6)
  1080. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近6月开卡最低额度'] = cip.getLastMonthMinCreditAmt(df, queryInfo["reportTime"], 6)
  1081. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近6月开卡平均额度'] = cip.getLastMonthAvgCreditAmt(df, queryInfo["reportTime"], 6)
  1082. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近12月开卡最高额度'] = cip.getLastMonthMaxCreditAmt(df, queryInfo["reportTime"], 12)
  1083. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近12月开卡最低额度'] = cip.getLastMonthMinCreditAmt(df, queryInfo["reportTime"], 12)
  1084. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近12月开卡平均额度'] = cip.getLastMonthAvgCreditAmt(df, queryInfo["reportTime"], 12)
  1085. if not creditDf.empty:
  1086. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡最近一次还款日期距今时长'] = cip.getLastPayDateMinDays(creditDf,queryInfo["reportTime"])
  1087. paySo = np.sum(creditDf['本月应还款'])
  1088. if(paySo)!=0:
  1089. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡还款比例'] = round(np.sum(creditDf['本月实还款'])/np.sum(creditDf['本月应还款']),2)
  1090. creditDfTmp = creditDf[creditDf['本月应还款']>0]
  1091. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡最高还款比例'] = round(np.max(np.divide(creditDfTmp['本月实还款'] , creditDfTmp['本月应还款'])), 2)
  1092. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡最低还款比例'] = round(np.min(np.divide(creditDfTmp['本月实还款'] , creditDfTmp['本月应还款'])), 2)
  1093. normalDf = df[(df['币种'] == '人民币元') & (df['账户状态'] == '正常') & (df['当前逾期期数']==0)];
  1094. notCloseDf = df[(df['账户状态'] != '销户')]
  1095. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常贷记卡账户数'] = normalDf.index.size
  1096. if not notCloseDf.empty and not normalDf.empty:
  1097. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常贷记卡账户数占比'] = round(normalDf.index.size/notCloseDf.index.size,2)
  1098. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常贷记卡已用额度'] = np.sum(normalDf['已用额度'])
  1099. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常且有余额的贷记卡账户数'] = normalDf[normalDf['已用额度']>0].index.size
  1100. if not creditDf.empty:
  1101. creditUseAmt = np.sum(creditDf['已用额度'])
  1102. if creditUseAmt!=0:
  1103. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常贷记卡账户余额占总余额比'] = round(np.sum(normalDf['已用额度']) / np.sum(creditDf['已用额度']), 2)
  1104. if notCloseDf.empty:
  1105. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常且有余额的贷记卡账户数占比'] = -99
  1106. else:
  1107. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常且有余额的贷记卡账户数占比'] = \
  1108. round(creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常且有余额的贷记卡账户数']/notCloseDf.index.size,3)
  1109. #当前正常贷记卡账户余额占总余额比
  1110. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡本月实还金额总和'] = np.sum(creditDf['本月实还款'])
  1111. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡本月应还金额总和'] = np.sum(creditDf['本月应还款'])
  1112. maxAmtDf = df[(df['币种'] == '人民币元')]
  1113. if not maxAmtDf.empty:
  1114. maxAmtDf = maxAmtDf.reset_index(drop=True)
  1115. maxAmtIndex = np.argmax(maxAmtDf['账户授信额度'])
  1116. maxOpenDate = maxAmtDf.loc[maxAmtIndex,:]['开立日期'];
  1117. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '额度最高的人民币贷记卡开卡距今月份数'] = utils.difMonthReportTime(maxOpenDate,queryInfo["reportTime"]);
  1118. # 名下贷记卡数量-状态正常
  1119. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态正常'] = df[(df['账户状态'] != '销户')].index.size
  1120. # 名下贷记卡数量-状态未激活
  1121. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态未激活'] = df[(df['账户状态'] == '未激活')].index.size
  1122. # 名下贷记卡数量-状态异常--异常包含(2-冻结,3-止付,5-呆帐,10-其他)
  1123. abnormalList = ['冻结','止付','呆帐','其他']
  1124. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态异常'] = df[(df['账户状态'].isin(abnormalList))].index.size
  1125. # 名下贷记卡比例-状态正常
  1126. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡比例-状态正常'] = round(creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态正常'] / df.index.size,2)
  1127. # 名下贷记卡比例-状态未激活
  1128. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡比例-状态未激活'] =round(creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态未激活'] / df.index.size,2)
  1129. # 名下贷记卡比例-状态异常
  1130. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡比例-状态异常'] = round(creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态异常'] / df.index.size,2)
  1131. #解析准贷记卡账户信息指标
  1132. def parseCreditCardMergeDfZ(df,payRcd):
  1133. if not df.empty:
  1134. overdueCreditCardRcdDf = payRcd[payRcd['账户编号'].isin(df['账户编号'].values)];
  1135. overdueCreditCardRcdDf = utils.replacePayRcdStatusOverdue(overdueCreditCardRcdDf)
  1136. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '本月应还款(合计)'] = np.nansum(df['透支余额'])
  1137. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '本月实还款(合计)'] = np.nansum(df['本月实还款'])
  1138. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '最近一次还款日期'] = np.max(df['最近一次还款日期'])
  1139. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前一共透支期数'] = cip.getCurOverdueNum(overdueCreditCardRcdDf);
  1140. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前一共透支总额'] = np.nansum(df['透支余额'])
  1141. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '透支180天以上未支付余额(合计)'] = np.nansum(df['透支180天以上未付余额'])
  1142. creditDf = df[(df['账户状态'] != '未激活') & (df['账户状态'] != '销户')]
  1143. if not creditDf.empty:
  1144. totalAmt = np.nansum(creditDf['账户授信额度'])
  1145. creditAmt = np.nansum(creditDf['透支余额'])
  1146. if totalAmt !=0:
  1147. #从“贷记卡信息”中提取,剔除未激活、销户后,所有账户透支金额/所有账户账户授信额度。
  1148. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '全部准贷记卡账户当前总额度使用率']=round(creditAmt/totalAmt,2)
  1149. #从“贷记卡信息”中提取,剔除未激活、销户后,MAX(单账户最高透支金额/单账户授信额度)
  1150. creditMaxDf = creditDf[creditDf['账户授信额度']>0]
  1151. if not creditMaxDf.empty:
  1152. creditMaxDf = creditMaxDf.fillna(0.0)
  1153. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '准贷记卡账户最高使用额度总的使用率'] = round(np.max(np.divide(creditMaxDf['最大透支余额'],creditMaxDf['账户授信额度'])),2)
  1154. creditMaxDf = creditDf[creditDf['最大透支余额'] > 0]
  1155. if not creditMaxDf.empty:
  1156. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前准贷记卡最大透支金额'] = np.max(creditMaxDf['最大透支余额'])
  1157. #从“贷记卡信息”中提取,剔除未激活、销户后,当前透支准贷记卡账户数/总准贷记卡账户数,透支账户判断:透支余额不为0的账户
  1158. creditDfTmp = creditDf[creditDf['透支余额']>0]
  1159. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前准贷记卡透支账户数占比'] = round(creditDfTmp.index.size / creditDf.index.size,2)
  1160. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前准贷记卡本月应还金额总和'] = np.nansum(df['透支余额'])
  1161. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前准贷记卡本月实还金额总和'] = np.nansum(df['本月实还款'])
  1162. #解析使用率 TODO 使用汇总计算还是使用明细计算
  1163. def parseUseRate():
  1164. # useRateDf.loc[useRateIndex, '贷记卡账户使用率(已用额度/授信总额)']
  1165. # 从“信贷交易授信及负债信息概要”中“非循环贷账户信息汇总”、“循环额度下分账户信息汇总”、“循环贷账户信息汇总”、“贷记卡账户信息汇总”和“准贷记卡账户信息汇总”里提取,SUM(
  1166. # 所有“余额”、“已用额度”和“透支余额”) / SUM(所有“授信总额”和“授信额度”)
  1167. loanUseAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户余额']
  1168. cycleCreditUseAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户余额']
  1169. cycleUseAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户余额']
  1170. creditUseAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡已用额度']
  1171. creditAmtUseZ = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡已用额度']
  1172. loanTotalAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户授信总额']
  1173. cycleCreditTotalAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户授信总额']
  1174. cycleTotalAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户授信总额']
  1175. creditTotalAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡授信总额']
  1176. creditAmtTotalZ = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡授信总额']
  1177. # if str(loanUseAmt)=="nan":
  1178. # loanUseAmt = 0;
  1179. # if str(cycleCreditUseAmt) == "nan":
  1180. # loanUseAmt = 0;
  1181. # if str(cycleCreditUseAmt) == "nan":
  1182. # loanUseAmt = 0;
  1183. useAmt = loanUseAmt+cycleCreditUseAmt+cycleUseAmt+creditUseAmt+creditAmtUseZ
  1184. totalAmt = loanTotalAmt+cycleCreditTotalAmt+cycleTotalAmt+creditTotalAmt+creditAmtTotalZ
  1185. if totalAmt !=0:
  1186. useRateDf.loc[useRateIndex, '全账户使用率(已用额度/授信总额)'] = round(useAmt / totalAmt,2)
  1187. if loanTotalAmt!=0:
  1188. useRateDf.loc[useRateIndex, '非循环贷账户使用率(已用额度/授信总额)'] = round(loanUseAmt / loanTotalAmt,2)
  1189. if cycleCreditTotalAmt !=0:
  1190. useRateDf.loc[useRateIndex, '循环额度下分账户使用率(已用额度/授信总额)'] = round(cycleCreditTotalAmt / cycleCreditTotalAmt,2)
  1191. if cycleTotalAmt !=0:
  1192. useRateDf.loc[useRateIndex, '循环贷账户使用率(已用额度/授信总额)'] = round(cycleUseAmt / cycleTotalAmt,2)
  1193. if creditTotalAmt !=0:
  1194. useRateDf.loc[useRateIndex, '贷记卡账户使用率(已用额度/授信总额)'] = round(creditUseAmt / creditTotalAmt,2)
  1195. if creditAmtTotalZ !=0:
  1196. useRateDf.loc[useRateIndex, '准贷记卡账户使用率(已用额度/授信总额)'] = round(creditAmtUseZ / creditAmtTotalZ,2)
  1197. #解析开户数
  1198. def parseOpenAccount(loanDf,creditCardDf,creditCardDfZ,recoveryInfoMergeDf,loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ):
  1199. reportTime = queryInfo["reportTime"];
  1200. openAccountDf.loc[openAccountIndex, '近3个月全账户开户数'] = cip.getOpenAccount(loanDf,reportTime,3)+cip.getOpenAccount(creditCardDf,reportTime,3)+cip.getOpenAccount(creditCardDfZ,reportTime,3)
  1201. openAccountDf.loc[openAccountIndex, '近6个月全账户开户数'] = cip.getOpenAccount(loanDf,reportTime,6)+cip.getOpenAccount(creditCardDf,reportTime,6)+cip.getOpenAccount(creditCardDfZ,reportTime,6)
  1202. openAccountDf.loc[openAccountIndex, '近9个月全账户开户数'] = cip.getOpenAccount(loanDf,reportTime,9)+cip.getOpenAccount(creditCardDf,reportTime,9)+cip.getOpenAccount(creditCardDfZ,reportTime,9)
  1203. openAccountDf.loc[openAccountIndex, '近12个月全账户开户数'] = cip.getOpenAccount(loanDf,reportTime,12)+cip.getOpenAccount(creditCardDf,reportTime,12)+cip.getOpenAccount(creditCardDfZ,reportTime,12)
  1204. openAccountDf.loc[openAccountIndex, '近24个月全账户开户数'] = cip.getOpenAccount(loanDf,reportTime,24)+cip.getOpenAccount(creditCardDf,reportTime,24)+cip.getOpenAccount(creditCardDfZ,reportTime,24)
  1205. openAccountDf.loc[openAccountIndex, '近3个月消费金融类账户开户数'] = lip.getOpenAccount(loanDf,reportTime,3,consts.bankList)
  1206. openAccountDf.loc[openAccountIndex, '近6个月消费金融类账户开户数'] = lip.getOpenAccount(loanDf,reportTime,6,consts.bankList)
  1207. openAccountDf.loc[openAccountIndex, '近9个月消费金融类账户开户数'] = lip.getOpenAccount(loanDf,reportTime,9,consts.bankList)
  1208. openAccountDf.loc[openAccountIndex, '近12个月消费金融类账户开户数'] = lip.getOpenAccount(loanDf,reportTime,12,consts.bankList)
  1209. openAccountDf.loc[openAccountIndex, '近24个月消费金融类账户开户数'] = lip.getOpenAccount(loanDf,reportTime,24,consts.bankList)
  1210. openAccountDf.loc[openAccountIndex, '近3个月贷款账户开户数'] = lip.getOpenAccount(loanDf,reportTime,3,"")
  1211. openAccountDf.loc[openAccountIndex, '近6个月贷款账户开户数'] = lip.getOpenAccount(loanDf,reportTime,6,"")
  1212. openAccountDf.loc[openAccountIndex, '近9个月贷款账户开户数'] = lip.getOpenAccount(loanDf,reportTime,9,"")
  1213. openAccountDf.loc[openAccountIndex, '近12个月贷款账户开户数'] = lip.getOpenAccount(loanDf,reportTime,12,"")
  1214. openAccountDf.loc[openAccountIndex, '近24个月贷款账户开户数'] = lip.getOpenAccount(loanDf,reportTime,24,"")
  1215. openAccountDf.loc[openAccountIndex, '近3个月贷记卡账户开户数'] = cip.getOpenAccount(creditCardDf,reportTime,3)
  1216. openAccountDf.loc[openAccountIndex, '近6个月贷记卡账户开户数'] = cip.getOpenAccount(creditCardDf,reportTime,6)
  1217. openAccountDf.loc[openAccountIndex, '近9个月贷记卡账户开户数'] = cip.getOpenAccount(creditCardDf,reportTime,9)
  1218. openAccountDf.loc[openAccountIndex, '近12个月贷记卡账户开户数'] = cip.getOpenAccount(creditCardDf,reportTime,12)
  1219. openAccountDf.loc[openAccountIndex, '近24个月贷记卡账户开户数'] = cip.getOpenAccount(creditCardDf,reportTime,24)
  1220. openAccountDf.loc[openAccountIndex, '近3个月准贷记卡账户开户数'] = cip.getOpenAccount(creditCardDfZ,reportTime,3)
  1221. openAccountDf.loc[openAccountIndex, '近6个月准贷记卡账户开户数'] = cip.getOpenAccount(creditCardDfZ,reportTime,6)
  1222. openAccountDf.loc[openAccountIndex, '近9个月准贷记卡账户开户数'] = cip.getOpenAccount(creditCardDfZ,reportTime,9)
  1223. openAccountDf.loc[openAccountIndex, '近12个月准贷记卡账户开户数'] = cip.getOpenAccount(creditCardDfZ,reportTime,12)
  1224. openAccountDf.loc[openAccountIndex, '近24个月准贷记卡账户开户数'] = cip.getOpenAccount(creditCardDfZ,reportTime,24)
  1225. #从“信贷交易信息明细”中“非循环贷账户”、“循环额度下分账户”、“循环贷账户”、“贷记卡账户”和“准贷记卡账户”里提取,5年里账户还款状态出现“1、2、3、4、5、6、7、D、Z、G、B”的账户数/所有账户数
  1226. overdueLoanPayRcdDf = loanPayRecordMergeDf[loanPayRecordMergeDf['账户编号'].isin(loanDf['账户编号'].values)]
  1227. overdueLoanPayRcdDf = utils.replacePayRcdStatusOverdue(overdueLoanPayRcdDf)
  1228. overdueLoanPayRcdDf = overdueLoanPayRcdDf[overdueLoanPayRcdDf['还款状态'] > 0]
  1229. overdueCreditPayRcdDf = creditCardPayRecordMergeDf[creditCardPayRecordMergeDf['账户编号'].isin(creditCardDf['账户编号'].values)]
  1230. overdueCreditPayRcdDf = utils.replacePayRcdStatusOverdue(overdueCreditPayRcdDf)
  1231. overdueCreditPayRcdDf = overdueCreditPayRcdDf[overdueCreditPayRcdDf['还款状态'] > 0]
  1232. overdueCreditPayRcdDfZ = creditCardPayRecordMergeDfZ[creditCardPayRecordMergeDfZ['账户编号'].isin(creditCardDfZ['账户编号'].values)]
  1233. overdueCreditPayRcdDfZ = utils.replacePayRcdStatusOverdue(overdueCreditPayRcdDfZ)
  1234. overdueCreditPayRcdDfZ = overdueCreditPayRcdDfZ[overdueCreditPayRcdDfZ['还款状态'] > 0]
  1235. loanAccountNum = loanPayRecordMergeDf['账户编号'].unique().size
  1236. creditAccountNum = creditCardPayRecordMergeDf['账户编号'].unique().size
  1237. creditAccountNumZ = creditCardPayRecordMergeDfZ['账户编号'].unique().size
  1238. overdueLoanNum = overdueLoanPayRcdDf['账户编号'].unique().size
  1239. overdueCreditNum = overdueCreditPayRcdDf['账户编号'].unique().size
  1240. overdueCreditNumZ = overdueCreditPayRcdDfZ['账户编号'].unique().size
  1241. if (loanAccountNum+creditAccountNum+creditAccountNumZ) >0:
  1242. openAccountDf.loc[openAccountIndex, '有过逾期记录的账户/全账户数'] = round((overdueLoanNum+overdueCreditNum+overdueCreditNumZ)/(loanAccountNum+creditAccountNum+creditAccountNumZ),2)
  1243. otherPerLoanDf = loanDf[loanDf['业务种类'].isin(consts.bankList)]
  1244. otherPerLoanNum = otherPerLoanDf.index.size;
  1245. overdueOtherPerLoanNum = otherPerLoanDf[otherPerLoanDf['账户编号'].isin(overdueLoanPayRcdDf['账户编号'].values)].index.size;
  1246. if otherPerLoanNum!=0:
  1247. openAccountDf.loc[openAccountIndex, '有过逾期记录的消费金融类账户/全消费金融类账户数'] = round(overdueOtherPerLoanNum/otherPerLoanNum,2)
  1248. if loanAccountNum!=0:
  1249. openAccountDf.loc[openAccountIndex, '有过逾期记录的贷款账户/全贷款账户数'] = round(overdueLoanNum/loanAccountNum,2)
  1250. if creditAccountNum!=0:
  1251. openAccountDf.loc[openAccountIndex, '有过逾期记录的贷记卡账户/全贷记卡账户数'] = round(overdueCreditNum/creditAccountNum,2)
  1252. if creditAccountNumZ!=0:
  1253. openAccountDf.loc[openAccountIndex, '有过透支记录的准贷记卡账户/全准贷记卡账户数']= round(overdueCreditNumZ/creditAccountNumZ,2)
  1254. # 0525新增
  1255. pledgeLoanDf = loanDf[loanDf['担保方式'] =='抵押']
  1256. pledgeCreditCardDf = creditCardDf[creditCardDf['担保方式'] == '抵押']
  1257. pledgeCreditCardDfZ = creditCardDfZ[creditCardDfZ['担保方式'] == '抵押']
  1258. isPledge = "否"
  1259. if pledgeLoanDf.index.size+pledgeCreditCardDf.index.size+pledgeCreditCardDfZ.index.size >0:
  1260. isPledge = "是"
  1261. creditLoanDf = loanDf[loanDf['担保方式'] == '信用/免担保']
  1262. creditCreditCardDf = creditCardDf[creditCardDf['担保方式'] == '信用/免担保']
  1263. creditCreditCardDfZ = creditCardDfZ[creditCardDfZ['担保方式'] == '信用/免担保']
  1264. isCredit = 0
  1265. if creditLoanDf.index.size + creditCreditCardDf.index.size + creditCreditCardDfZ.index.size > 0:
  1266. isCredit = creditLoanDf.index.size + creditCreditCardDf.index.size + creditCreditCardDfZ.index.size
  1267. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '是否存在担保方式为抵押的贷款'] = isPledge
  1268. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '担保方式为信用的贷款数量'] = isCredit
  1269. #解析24期还款状态指标
  1270. def parsePayRcdStatus(loanMergeDf, creditCardMergeDf, creditCardMergeDfZ,loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ):
  1271. #creditCardPayRecordMergeDf
  1272. # 去掉外币
  1273. creditCardMergeDf = creditCardMergeDf[creditCardMergeDf['币种']=='人民币元']
  1274. creditCardPayRecordMergeDf = creditCardPayRecordMergeDf[creditCardPayRecordMergeDf['账户编号'].isin(creditCardMergeDf['账户编号'].values)]
  1275. reportTime = queryInfo["reportTime"];
  1276. reportTime = str(np.datetime64(reportTime, "M"))+"-02"#06-02,统计24期还款状态报告期,按每月的2号,避免chu'xian
  1277. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近3月逾期期数大于或等于“1”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,3)
  1278. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近6月逾期期数大于或等于“1”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,6)
  1279. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近12月逾期期数大于或等于“1”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,12)
  1280. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24月逾期期数大于或等于“1”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,24)
  1281. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近6月逾期期数大于或等于“2”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,6)
  1282. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近12月逾期期数大于或等于“2”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,12)
  1283. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24月逾期期数大于或等于“2”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,24)
  1284. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近6月逾期期数大于或等于“3”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,6)
  1285. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近12月逾期期数大于或等于“3”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,12)
  1286. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24月逾期期数大于或等于“3”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,24)
  1287. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近12月逾期期数大于或大等于“4”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,4,12)
  1288. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24月逾期期数大于或等于“4”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,4,24)
  1289. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近3月逾期期数大于或等于“1”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,3)
  1290. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近6月逾期期数大于或等于“1”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,6)
  1291. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近12月逾期期数大于或等于“1”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,12)
  1292. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近24月逾期期数大于或等于“1”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,24)
  1293. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近6月逾期期数大于或等于“2”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,6)
  1294. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近12月逾期期数大于或等于“2”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,12)
  1295. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近24月逾期期数大于或等于“2”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,24)
  1296. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近6月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,6)
  1297. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近12月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,12)
  1298. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近24月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,24)
  1299. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近12月逾期期数大于或等于“4”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,4,12)
  1300. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近24月逾期期数大于或等于“4”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,4,24)
  1301. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近6月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,6)
  1302. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近12月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,12)
  1303. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近24月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,24)
  1304. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近6月逾期期数大于或等于“4”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,4,6)
  1305. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近12月逾期期数大于或等于“4”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,4,12)
  1306. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近24月逾期期数大于或等于“4”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,4,24)
  1307. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近3月逾期期数大于或等于“1”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,3)\
  1308. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,3)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,1,3)
  1309. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近6月逾期期数大于或等于“1”的次数'] = \
  1310. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,6)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,6)\
  1311. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,1,6)
  1312. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近12月逾期期数大于或等于“1”的次数'] = \
  1313. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,12)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,12)\
  1314. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,1,12)
  1315. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近24月逾期期数大于或等于“1”的次数'] = \
  1316. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,24)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,24)\
  1317. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,1,24)
  1318. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近6月逾期期数大于或等于“2”的次数'] = \
  1319. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,6)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,6)\
  1320. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,2,6)
  1321. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近12月逾期期数大于或等于“2”的次数'] = \
  1322. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,12)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,12)\
  1323. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,2,12)
  1324. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近24月逾期期数大于或等于“2”的次数'] = \
  1325. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,24)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,24)\
  1326. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,2,24)
  1327. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近6月逾期期数大于或等于“3”的次数'] = \
  1328. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,6)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,6)\
  1329. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,6)
  1330. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近12月逾期期数大于或等于“3”的次数'] = \
  1331. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,12)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,12)\
  1332. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,12)
  1333. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近24月逾期期数大于或等于“3”的次数'] = \
  1334. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,24)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,24)\
  1335. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,24)
  1336. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近12月逾期期数大于或等于“4”的次数'] = \
  1337. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,4,12)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,4,12)\
  1338. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,4,12)
  1339. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近24月逾期期数大于或等于“4”的次数'] = \
  1340. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,4,24)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,4,24)\
  1341. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,4,24)
  1342. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24个月是否出现"G"'] = prp.isExistsInd(loanPayRecordMergeDf,reportTime,"G",24)
  1343. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近24个月是否出现"G"'] = prp.isExistsInd(creditCardPayRecordMergeDf,reportTime,"G",24)
  1344. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近24个月是否出现"G"'] = prp.isExistsInd(creditCardPayRecordMergeDfZ,reportTime,"G",24)
  1345. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24个月是否出现"Z"'] = prp.isExistsInd(loanPayRecordMergeDf,reportTime,"Z",24)
  1346. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有贷款账户过去24个月存在逾期的账户数目'] = prp.getLoanOverdueCount(loanPayRecordMergeDf,reportTime,24)
  1347. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有贷款账户过去24个月状态正常账户数目'] = prp.getLoanNormalCount(loanPayRecordMergeDf,reportTime,24)
  1348. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有贷记卡账户过去24个月存在逾期的账户数目'] = prp.getLoanOverdueCount(creditCardPayRecordMergeDf,reportTime,24)
  1349. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有贷记卡账户过去24个月状态正常的账户数目'] = prp.getLoanNormalCount(creditCardPayRecordMergeDf,reportTime,24)
  1350. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有准贷记卡账户过去24个月存在逾期的账户数目'] = prp.getLoanOverdueCount(creditCardPayRecordMergeDfZ,reportTime,24)
  1351. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有准贷记卡账户过去24个月状态正常的账户数目'] = prp.getLoanNormalCount(creditCardPayRecordMergeDfZ,reportTime,24)
  1352. payRcdStatusDf.loc[payRcdStatusIndex, '用户过去3个月最大逾期期数'] = prp.getPayRcdMaxOverdueNumAllAccout(loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ,reportTime,3)
  1353. payRcdStatusDf.loc[payRcdStatusIndex, '用户过去6个月最大逾期期数'] = prp.getPayRcdMaxOverdueNumAllAccout(loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ,reportTime,6)
  1354. payRcdStatusDf.loc[payRcdStatusIndex, '用户过去12个月最大逾期期数'] = prp.getPayRcdMaxOverdueNumAllAccout(loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ,reportTime,12)
  1355. payRcdStatusDf.loc[payRcdStatusIndex, '用户过去24个月最大逾期期数'] = prp.getPayRcdMaxOverdueNumAllAccout(loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ,reportTime,24)
  1356. #概要信息里的字段,从还款状态计算
  1357. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '该用户过去5年出现逾期的所有账户数目'] = \
  1358. prp.getLoanOverdueCount(loanPayRecordMergeDf,reportTime,24*5)+prp.getLoanOverdueCount(creditCardPayRecordMergeDf,reportTime,24*5)\
  1359. +prp.getLoanOverdueCount(creditCardPayRecordMergeDfZ,reportTime,24*5)
  1360. #解析贷款还款记录指标
  1361. def parseCreditCardMergeAndPayRecordDf(df,payRcdDf):
  1362. if not df.empty and not payRcdDf.empty:
  1363. # 正常
  1364. normalDf = df[(df['账户状态'] != '未激活') & (df['账户状态'] != '销户') & (df['账户状态'] != '呆账')]
  1365. if not normalDf.empty:
  1366. overduePayRcdDf = payRcdDf[payRcdDf['账户编号'].isin(normalDf['账户编号'].values)]
  1367. overduePayRcdDf = utils.replacePayRcdStatus(overduePayRcdDf)
  1368. # 计算当前贷款,为还款记录的最后一期 0529
  1369. curOverduePayRcdDf = overduePayRcdDf.sort_values(by=["账户编号", "还款日期"], ascending=(True, False))
  1370. curOverduePayRcdDf = curOverduePayRcdDf.groupby(['账户编号']).head(1)
  1371. curOverduePayRcdDf = curOverduePayRcdDf[curOverduePayRcdDf['还款状态'] > 0]
  1372. # 临时保存,不用过滤还款状态为0的
  1373. payRcdMaxOverdueDf = overduePayRcdDf;
  1374. # overduePayRcdDf = overduePayRcdDf[overduePayRcdDf['还款状态'] > 0]
  1375. # creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡逾期账户数'] = curOverduePayRcdDf['账户编号'].unique().size
  1376. #从“贷记卡信息”中提取,剔除“账户状态”为未激活、销户、呆账、呆帐后,“当前信用卡逾期账户数”/未销户贷记卡账户数(剔除“账户状态”为未激活、销户、呆账、呆帐后记录条数)
  1377. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡逾期账户数占比'] = round(curOverduePayRcdDf['账户编号'].unique().size / normalDf.index.size, 2)
  1378. #从“贷记卡信息”中提取,剔除“账户状态”为未激活、销户、呆账、呆帐后,对(当前信用卡逾期账户数)按“开户机构代码”去重统计账户状态为逾期,按按“开户机构代码”去重后的记录条数
  1379. overdueCreditCardDf = normalDf[normalDf['账户编号'].isin(curOverduePayRcdDf['账户编号'].values)]
  1380. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡逾期机构数'] = overdueCreditCardDf['发卡机构'].unique().size
  1381. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡逾期机构数占比'] = round(creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡逾期机构数'] / normalDf['发卡机构'].unique().size, 2)
  1382. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近3月贷记卡最大逾期期数'] = cip.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 3);
  1383. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近6月贷记卡最大逾期期数'] = cip.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 6);
  1384. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近9月贷记卡最大逾期期数'] = cip.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 9);
  1385. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近12月贷记卡最大逾期期数'] = cip.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 12);
  1386. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近24月贷记卡最大逾期期数'] = cip.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 24);
  1387. reportTime = queryInfo["reportTime"]
  1388. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近24月贷记卡最大逾期距离现在的月数'] = cip.getPayRcdMaxOverdueNumMonth(payRcdMaxOverdueDf,normalDf,reportTime, 24);
  1389. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近3个月贷记卡最大连续逾期月份数'] = cip.getContinuousOverdueMonth(payRcdMaxOverdueDf,normalDf,3);
  1390. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近6个月贷记卡最大连续逾期月份数'] = cip.getContinuousOverdueMonth(payRcdMaxOverdueDf,normalDf,6);
  1391. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近9个月贷记卡最大连续逾期月份数'] = cip.getContinuousOverdueMonth(payRcdMaxOverdueDf,normalDf,9);
  1392. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近12个月贷记卡最大连续逾期月份数'] = cip.getContinuousOverdueMonth(payRcdMaxOverdueDf,normalDf,12);
  1393. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近24个月贷记卡最大连续逾期月份数'] = cip.getContinuousOverdueMonth(payRcdMaxOverdueDf,normalDf,24);
  1394. payRcdTimesDf = payRcdDf[payRcdDf['账户编号'].isin(normalDf['账户编号'].values)]
  1395. payRcdTimesDf = payRcdTimesDf.sort_values(by=["账户编号", "还款日期"], ascending=(True, False))
  1396. payRcdTimesDf = payRcdTimesDf.groupby(['账户编号']).head(24)
  1397. payStatus = ["G", "D", "C", "N", "M", "1", "2", "3", "4", "5", "6", "7"]
  1398. payRcdTimesDf = payRcdTimesDf[payRcdTimesDf['还款状态'].isin(payStatus)]
  1399. payRcdTimes = payRcdTimesDf.groupby(['账户编号'])['还款状态'].count()
  1400. #从“贷记卡信息”中提取,剔除未激活、销户、呆账、呆帐后,各账户的还款次数统计“24个月(账户)还款状态”包含"G","D","C","N","M"及数字的个数
  1401. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡24期还款记录次数'] = np.max(payRcdTimes)
  1402. # 解析被追偿信息汇总
  1403. def parseRecoveryInfoMergeDf(df):
  1404. if not df.empty:
  1405. recoveryMaxPayDf = df[df['债权转移时的还款状态'] !='--']
  1406. recoveryStatusCs = df[df['账户状态'] == '催收']
  1407. if not recoveryMaxPayDf.empty:
  1408. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '债权转移时的最大还款状态'] = np.max(recoveryMaxPayDf['债权转移时的还款状态']);
  1409. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '债权转移时属于催收状态的账户数'] = recoveryStatusCs.index.size;
  1410. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '债权转移时属于催收状态的账户数/被追偿信息总数'] = round(recoveryStatusCs.index.size/df.index.size,2);
  1411. #creditTradeDetailDf_recoveryInfo
  1412. # 被追偿账户总数
  1413. creditTradeDetailDf_recoveryInfo.loc[recoveryInfoIndex,'被追偿账户总数'] = df.index.size;
  1414. creditTradeDetailDf_recoveryInfo.loc[recoveryInfoIndex, '被追偿业务种类'] = df['业务种类'].unique().size;
  1415. creditTradeDetailDf_recoveryInfo.loc[recoveryInfoIndex, '最新一笔被追偿债券接收时间'] = np.max(df['债权接收日期']);
  1416. creditTradeDetailDf_recoveryInfo.loc[recoveryInfoIndex, '总债权金额'] = np.max(df['债权金额']);
  1417. creditTradeDetailDf_recoveryInfo.loc[recoveryInfoIndex, '债权转移时的最大还款状态'] = np.max(recoveryMaxPayDf['债权转移时的还款状态']);
  1418. def main(pdf_path):
  1419. # 解析pdf开始
  1420. fileName = os.path.basename(pdf_path)
  1421. print(fileName)
  1422. with pdfplumber.open(pdf_path) as pdf:
  1423. for p in range(0, len(pdf.pages)):
  1424. page = pdf.pages[p]
  1425. # first_page = pdf.pages[1]
  1426. # if p == 3:
  1427. # print(3)
  1428. tables = page.extract_tables();
  1429. for i in range(0, len(tables)):
  1430. table = tables[i]
  1431. df = pd.DataFrame(table);
  1432. # if p==12:
  1433. # logger.info(p)
  1434. if len(keyList) > 1 and i == 0: # 判断是否被分页了
  1435. if not utils.checkHeader(df, allHeaders):
  1436. key = keyList[-1];
  1437. dfObj = dfMap[key]
  1438. # dfObj["nextDf"]=df;
  1439. # 贷款信息 贷记卡信息 强制执行记录
  1440. if key == "loanDfs" or key == "creditCardDfs" or key == "creditCardDfsZ" or key == "forceExecRcdDfs" or key == 'recoveryInfoDfs' or key == "housingFundRcdDfs": # 属于列表
  1441. lastDfObj = dfObj["dfs"][-1];
  1442. lastDfObj["isByPage"] = str(p + 1);
  1443. if len(dfObj["dfs"][-1]["df"].columns) == len(df.columns): # 列数相同
  1444. lastDfObj["df"] = pd.concat([lastDfObj["df"], df], axis=0,ignore_index=True); # 去最后一个进行合并
  1445. # print("key-" + key + "-page-" + str(p + 1) + "-" + "###列数相同####-被分页")
  1446. else:
  1447. # print("key-" + key + "-page-" + str(p + 1) + "-" + "列数不同-被分页")
  1448. lastDfObj["df"] = pd.concat([lastDfObj["df"], df], axis=0, ignore_index=True);
  1449. else: # 查询记录明细 为单个列表
  1450. dfObj["isByPage"] = str(p + 1);
  1451. logger.info(fileName+"#"+key)
  1452. if len(dfObj["df"].columns) == len(df.columns):
  1453. # print("key-" + key + "-page-" + str(p + 1) + "-" + "###列数相同####-被分页")
  1454. dfObj["df"] = pd.concat([dfObj["df"], df], axis=0, ignore_index=True)
  1455. else:
  1456. # print("key-" + key + "-page-" + str(p + 1) + "-" + "列数不同-被分页")
  1457. dfObj["df"] = pd.concat([dfObj["df"], df], axis=0, ignore_index=True)
  1458. # dfObj["nextDf"] = df;
  1459. # 如果列数相等合并df
  1460. continue;
  1461. headerList0 = df.loc[0, :].tolist() # 第0行为表头
  1462. headerList0 = list(filter(None, headerList0))
  1463. headerList1 = []
  1464. if df.index.size>1:
  1465. headerList1 = df.loc[1, :].tolist() # 第1行为表头
  1466. headerList1 = list(filter(None, headerList1))
  1467. if headerList1 == queryInfoDf_header: # 被查询信息 第二行为数据
  1468. queryInfoDf = df;
  1469. dfKey = "queryInfoDf"
  1470. dfMap[dfKey]["df"] = df;
  1471. keyList.append(dfKey);
  1472. elif headerList0 == identity_header: # 身份信息
  1473. identityDf = df[:2] # 截取前2行
  1474. addressDf = df.loc[2:4,:] # 截取3到4行的第一和6
  1475. addressDf = addressDf.reset_index(drop=True)
  1476. mobileDf = utils.replaceDateColIdx(df[5:df.index.size], 5)
  1477. identityDf = pd.concat([identityDf, addressDf], axis=1, ignore_index=True) # 横向合并
  1478. dfKey = "identityDf"
  1479. dfMap[dfKey]["df"] = identityDf;
  1480. keyList.append(dfKey);
  1481. # 组装电话号码df
  1482. dfMap[dfKey]["mobileDf"] = mobileDf
  1483. elif headerList0 == mateDf_header: # 配偶信息
  1484. mateDf = df;
  1485. dfKey = "mateDf"
  1486. dfMap[dfKey]["df"] = df;
  1487. keyList.append(dfKey);
  1488. elif headerList0 == liveInfoDf_header: # 居住信息
  1489. mateDf = df;
  1490. dfKey = "liveInfoDf"
  1491. dfMap[dfKey]["df"] = df;
  1492. keyList.append(dfKey);
  1493. elif headerList0 == occupationInfo_header: # 职业信息 可能存在分页
  1494. occupationDf = df;
  1495. dfKey = "occupationDf"
  1496. dfMap[dfKey]["df"] = df;
  1497. keyList.append(dfKey);
  1498. # elif headerList0 == queryInfoBrief_header0 and headerList1 == queryInfoBrief_header1: # 查询信息概要 第二行为数据
  1499. # queryInfoBriefDf = df;
  1500. # dfKey = "queryInfoBriefDf"
  1501. # dfMap[dfKey]["df"] = df;
  1502. # keyList.append(dfKey);
  1503. elif headerList0 == loanTradeInfo_header: # 信贷交易信息
  1504. loanTradeInfoDf = df;
  1505. dfKey = "loanTradeInfoDf";
  1506. dfMap[dfKey]["df"] = df;
  1507. keyList.append(dfKey);
  1508. elif headerList1 == recoveryInfoSumDf_header: # 被追偿信息汇总
  1509. recoveryInfoSumDf = df;
  1510. dfKey = "recoveryInfoSumDf";
  1511. dfMap[dfKey]["df"] = df;
  1512. keyList.append(dfKey);
  1513. elif headerList1 == badDebtsInfoSumDf_header: # 呆账信息
  1514. badDebtsInfoSumDf = df;
  1515. dfKey = "badDebtsInfoSumDf";
  1516. dfMap[dfKey]["df"] = df;
  1517. keyList.append(dfKey);
  1518. elif headerList1 == overdueInfoSumDf_header: # 逾期透资信息汇总
  1519. overdueInfoSumDf = df;
  1520. dfKey = "overdueInfoSumDf";
  1521. dfMap[dfKey]["df"] = df;
  1522. keyList.append(dfKey);
  1523. elif headerList0 == loanAccountInfoSumDf_header0 and headerList1 == loanAccountInfoSumDf_header1: # 非循环贷账户信息汇总
  1524. loanAccountInfoSumDf = df;
  1525. dfKey = "loanAccountInfoSumDf";
  1526. dfMap[dfKey]["df"] = df;
  1527. keyList.append(dfKey);
  1528. elif headerList0 == creditCardInfoSumDf_header0 and headerList1 == creditCardInfoSumDf_header1: # 贷记卡信息汇总
  1529. creditCardInfoSumDf = df;
  1530. dfKey = "creditCardInfoSumDf";
  1531. dfMap[dfKey]["df"] = df;
  1532. keyList.append(dfKey);
  1533. elif headerList0 == creditCardInfoSumDfZ_header0 and headerList1 == creditCardInfoSumDfZ_header1: # 准贷记卡信息汇总 目前没有数据
  1534. dfKey = "creditCardInfoSumDfZ";
  1535. dfMap[dfKey]["df"] = df;
  1536. keyList.append(dfKey);
  1537. elif headerList0 == repaymentSumDf_header0:#相关还款责任汇总
  1538. dfKey = "repaymentSumDf";
  1539. dfMap[dfKey]["df"] = df;
  1540. keyList.append(dfKey);
  1541. elif headerList0 == publicInfoBriefDf_header0: #公共信息概要
  1542. dfKey = "publicInfoBriefDf";
  1543. dfMap[dfKey]["df"] = df;
  1544. keyList.append(dfKey);
  1545. elif headerList0 == queryRecordSumDf_header0:#查询记录汇总
  1546. dfKey = "queryRecordSumDf";
  1547. dfMap[dfKey]["df"] = df;
  1548. keyList.append(dfKey);
  1549. elif headerList0 == loan_header: # 贷款账户 包括循环贷,非循环贷 循环额度下分账户
  1550. dfKey = "loanDfs";
  1551. dfMap[dfKey]["dfs"].append({"df": df});
  1552. keyList.append(dfKey);
  1553. elif headerList0 == creditCard_header: # 贷记卡账户
  1554. dfKey = "creditCardDfs";
  1555. dfMap[dfKey]["dfs"].append({"df": df});
  1556. keyList.append(dfKey);
  1557. elif headerList0 == creditCardZ_header: # 准贷记卡账户 还不能和贷记卡合并
  1558. dfKey = "creditCardDfsZ";
  1559. dfMap[dfKey]["dfs"].append({"df": df});
  1560. keyList.append(dfKey);
  1561. elif headerList0 == queryRecordDetailDf_header: # 查询记录明细
  1562. dfKey = "queryRecordDetailDf";
  1563. dfMap[dfKey]["df"] = df;
  1564. keyList.append(dfKey);
  1565. elif headerList0 == housingFundRcdDfs_header: # 查询记录明细
  1566. dfKey = "housingFundRcdDfs";
  1567. dfMap[dfKey]["dfs"].append({"df": df});
  1568. keyList.append(dfKey);
  1569. elif headerList0 == forceExecRcdDfs_header: # 强制执行记录
  1570. dfKey = "forceExecRcdDfs";
  1571. dfMap[dfKey]["dfs"].append({"df": df});
  1572. keyList.append(dfKey);
  1573. elif headerList0 == recoveryInfoDfs_header: # 被追偿信息
  1574. dfKey = "recoveryInfoDfs";
  1575. dfMap[dfKey]["dfs"].append({"df": df});
  1576. keyList.append(dfKey);
  1577. # 设置分页
  1578. dfMap[dfKey]["page"] = p + 1;
  1579. logger.info(fileName+"#"+"组装pdf数据完成")
  1580. logger.info(fileName+"#"+"解析基础pdf数据开始")
  1581. # 打印结果解析并构建指标
  1582. for key in dfMap:
  1583. tempDfObjx = dfMap[key];
  1584. if tempDfObjx.__contains__("page"):
  1585. logger.info(fileName+"#"+key + "-page-" + str(tempDfObjx["page"]))
  1586. if tempDfObjx.__contains__("dfs"):
  1587. if key == "loanDfs": # 贷款账户
  1588. for idx in range(0, len(tempDfObjx["dfs"])):
  1589. tempDfObj = tempDfObjx["dfs"][idx];
  1590. loanAccountDfs.append(dfParser.mergeLoanDf(tempDfObj, idx,queryInfo['reportTime']))
  1591. elif key == "creditCardDfs": # 贷记卡账户合并
  1592. for idx in range(0, len(tempDfObjx["dfs"])):
  1593. tempDfObj = tempDfObjx["dfs"][idx];
  1594. tempCreditCardDf = dfParser.mergeCreditCardDf(tempDfObj, idx,queryInfo['reportTime']);
  1595. if tempCreditCardDf!=None:
  1596. creditCardAccountDfs.append(tempCreditCardDf)
  1597. elif key == "creditCardDfsZ": # 贷记卡账户合并
  1598. for idx in range(0, len(tempDfObjx["dfs"])):
  1599. tempDfObj = tempDfObjx["dfs"][idx];
  1600. tempCreditCardDfZ = dfParser.mergeCreditCardDfZ(tempDfObj, idx,queryInfo['reportTime'])
  1601. if tempCreditCardDfZ!=None:
  1602. creditCardAccountDfsZ.append(tempCreditCardDfZ)
  1603. elif key == "recoveryInfoDfs": # 贷记卡账户合并
  1604. for idx in range(0, len(tempDfObjx["dfs"])):
  1605. tempDfObj = tempDfObjx["dfs"][idx];
  1606. recoveryInfoAccountDfs.append(dfParser.mergeRecoveryInfoDf(tempDfObj, idx, queryInfo['reportTime']))
  1607. elif key == "housingFundRcdDfs": # 贷记卡账户合并
  1608. for idx in range(0, len(tempDfObjx["dfs"])):
  1609. tempDfObj = tempDfObjx["dfs"][idx];
  1610. housingFundRcdAccountDfs.append(dfParser.mergeHousingFundRcdDf(tempDfObj, idx, queryInfo['reportTime']))
  1611. else: # 其他
  1612. for tempDfObj in (tempDfObjx["dfs"]):
  1613. if tempDfObj.__contains__("isByPage"):
  1614. logger.info(fileName+"#"+key + "============其他被分页页数============" + str(tempDfObj["isByPage"]))
  1615. # logger.info(fileName+"#"+tempDfObj["df"].values)
  1616. else: # 单笔
  1617. tempDfObj = tempDfObjx;
  1618. if tempDfObj.__contains__("isByPage"):
  1619. logger.info(fileName+"#"+key + "============被分页页数================" + str(tempDfObj["isByPage"]))
  1620. # logger.info(fileName+"#"+tempDfObj["df"].values)
  1621. if key == "queryInfoDf": # 解析被查询信息
  1622. parseQueryInfo(tempDfObj);
  1623. # print("\033[1;31m +查询信息+ \033[0m")
  1624. # print(queryInfo)
  1625. elif key == "identityDf": # 身份信息
  1626. parseIdentity(tempDfObj)
  1627. # print("\033[1;31m +身份信息+ \033[0m")
  1628. # print(identity)
  1629. elif key == "mateDf": # 配偶信息
  1630. parseMate(tempDfObj)
  1631. # print("\033[1;31m +配偶信息+ \033[0m")
  1632. # print(mate)
  1633. elif key == "liveInfoDf": # 居住信息
  1634. parseLiveInfo(tempDfObj)
  1635. # print("\033[1;31m +居住信息+ \033[0m")
  1636. elif key == "occupationDf": # 居住信息
  1637. parseOccupationInfoDf(tempDfObj)
  1638. elif key == "loanTradeInfoDf": # 信贷交易信息提示
  1639. parseLoanTradeInfo(tempDfObj);
  1640. # print("\033[1;31m +信贷交易信息提示+ \033[0m")
  1641. # print(loanTradeInfo)
  1642. elif key == "badDebtsInfoSumDf": # 呆账信息汇总
  1643. parseBadDebtsInfoSumDf(tempDfObj)
  1644. # print("\033[1;31m +呆账信息汇总+ \033[0m")
  1645. # print(overdueBrief)
  1646. elif key == "recoveryInfoSumDf": # 被追偿信息汇总-资产处置和垫款
  1647. parseRecoveryInfoSum(tempDfObj)
  1648. # print("\033[1;31m +资产处置和垫款+ \033[0m")
  1649. # print(overdueBrief)
  1650. elif key == "overdueInfoSumDf": # 逾期(透支)信息汇总
  1651. parseOverdueInfoSum(tempDfObj)
  1652. # print("\033[1;31m +逾期(透支)信息汇总+ \033[0m")
  1653. # print(overdueInfo)
  1654. elif key == "loanAccountInfoSumDf": # 非循环贷账户信息汇总 TODO
  1655. parseLoanAccountInfoSum(tempDfObj)
  1656. elif key == "cycleCreditAccountInfoSumDf":#循环额度
  1657. parseCycleCreditAccountInfoSum(tempDfObj)
  1658. elif key == "cycleLoanAccountInfoSumDf":#循环贷
  1659. parseCyleLoanAccountInfoSum(tempDfObj)
  1660. elif key == "creditCardInfoSumDf":#贷记卡
  1661. parseCreditCardInfoSum(tempDfObj)
  1662. elif key == "creditCardInfoSumDfZ": # 准贷记卡
  1663. parseCreditCardInfoSumZ(tempDfObj)
  1664. elif key == "repaymentSumDf": # 相关还款责任
  1665. parseRepaymentSum(tempDfObj)
  1666. elif key == "publicInfoBriefDf":
  1667. parsePublicInfoBrief(tempDfObj);
  1668. elif key == "queryRecordSumDf":
  1669. parseQueryRecordSum(tempDfObj);
  1670. elif key == "queryRecordDetailDf": # 查询记录明细
  1671. parseQueryInfoDetail(tempDfObj)#
  1672. logger.info(fileName+"#"+"解析基础pdf数据完成")
  1673. result = "{"
  1674. # 基本信息
  1675. # result+=("\033[1;34m +身份信息+ \033[0m")+"\n"
  1676. result+=utils.toJson(identityInfoDf)+","
  1677. result += utils.toJson(mateInfoDf) + ","
  1678. result += utils.toJson(liveInfoDf) + ","
  1679. result += utils.toJson(occupationInfoDf) + ","
  1680. # result+=("\033[1;34m +概要信息+ \033[0m")+","
  1681. # result+=("\033[1;34m +信贷交易信息提示+ \033[0m")+","
  1682. # result+=utils.toJson(briefInfoDf_loanTradeInfo)+","
  1683. result += "briefInfoDf_loanTradeInfo" + "," # 占位符
  1684. # result+=("\033[1;34m +被追偿信息汇总及呆账信息汇总+ \033[0m")+","
  1685. result+="briefInfoDf_recoveryInfoSum"+"," #占位符
  1686. result += utils.toJson(briefInfoDf_badDebtsInfoSum) + ","
  1687. # result+=("\033[1;34m +逾期(透支)信息汇总+ \033[0m")+","
  1688. #此信息先占位
  1689. result+="briefInfoDf_overdueInfoSum"+","
  1690. # result+=("\033[1;34m +信贷交易授信及负债信息概要+ \033[0m")+","
  1691. result+=utils.toJson(briefInfoDf_loanTradeCreditInfo)+","
  1692. #公共信息
  1693. result += utils.toJson(publicInfoBriefDf) + ","
  1694. #查询记录汇总
  1695. result += utils.toJson(queryRecordSumDf) + ","
  1696. # 单独输出贷款df
  1697. # logger.info(fileName+"#"+"\033[1;34m +贷款信息Dataframe+ \033[0m")
  1698. # logger.info(fileName+"#"+dfParser.dfHeaderLoan)
  1699. logger.info(fileName+"#"+pdf_path+"解析贷款数据开始")
  1700. loanMergeDf = pd.DataFrame(columns=dfParser.dfHeaderLoan)
  1701. loanPayRecordMergeDf = pd.DataFrame(columns=dfParser.dfHeaderLoanPayRecord)
  1702. loanSpecialTradeMergeDf = pd.DataFrame(columns=dfParser.dfHeaderLoanSpecialTrade)#特殊交易
  1703. # 输出数据
  1704. for loanDfObj in loanAccountDfs:
  1705. loanMergeDf = pd.concat([loanMergeDf, loanDfObj["loanDf"]], axis=0, ignore_index=True);
  1706. loanPayRecordMergeDf = pd.concat([loanPayRecordMergeDf, loanDfObj["loanPayRecordDf"]], axis=0,ignore_index=True);
  1707. loanSpecialTradeMergeDf = pd.concat([loanSpecialTradeMergeDf, loanDfObj["specialTradeDf"]], axis=0, ignore_index=True);
  1708. # logger.info(fileName+"#"+loanMergeDf.values)
  1709. # logger.info(fileName+"#"+"\033[1;34m +贷款信息还款记录Dataframe+ \033[0m")
  1710. # logger.info(fileName+"#"+dfParser.dfHeaderLoanPayRecord)
  1711. # logger.info(fileName+"#"+loanPayRecordMergeDf.values)
  1712. #
  1713. #==============================信贷交易明细 ===============================
  1714. #被追偿信息
  1715. # 被追偿信息合并df
  1716. recoveryInfoMergeDf = pd.DataFrame(columns=dfParser.dfHeaderRecoveryInfo)
  1717. for recoveryInfoDfObj in recoveryInfoAccountDfs:
  1718. recoveryInfoMergeDf = pd.concat([recoveryInfoMergeDf, recoveryInfoDfObj["recoveryInfoDf"]], axis=0,
  1719. ignore_index=True);
  1720. parseRecoveryInfoMergeDf(recoveryInfoMergeDf);
  1721. #被追偿信息
  1722. result = result.replace("briefInfoDf_recoveryInfoSum", utils.toJson(briefInfoDf_recoveryInfoSum))#替换汇总中的指标
  1723. result += utils.toJson(creditTradeDetailDf_recoveryInfo) + "," #设置占位符,由于存在概要的指标在明细中计算
  1724. #特殊交易
  1725. parseSpecialTrade(loanSpecialTradeMergeDf)
  1726. result += utils.toJson(creditTradeDetailHeader_specialTrade) + ","
  1727. # 信贷交易明细-解析非循环贷账户
  1728. parseLoanAccountInfo(loanMergeDf);
  1729. result += utils.toJson(creditTradeDetailDf_loanAccountInfo) + ","
  1730. #循环额度分账户
  1731. parseCycleCreditAccountInfo(loanMergeDf);
  1732. result += utils.toJson(creditTradeDetailDf_cycleCreditAccountInfo) + ","
  1733. #循环贷
  1734. parseCycleLoanAccountInfo(loanMergeDf);
  1735. result += utils.toJson(creditTradeDetailDf_cycleLoanAccountInfo) + ","
  1736. # 解析贷款账户指标
  1737. parseLoanMergeDf(loanMergeDf);
  1738. # 解析还款记录相关指标
  1739. parseLoanMergeAndPayRecordDf(loanMergeDf, loanPayRecordMergeDf);
  1740. # logger.info(fileName+"#"+loanAccountInfo)
  1741. # logger.info(fileName+"#"+consts.loanAccountInfoHeader)
  1742. # logger.info(fileName+"#"+loanAccountInfoDf.values)
  1743. # result+=("\033[1;34m +贷款账户信息+ \033[0m")+","
  1744. result+=utils.toJson(loanAccountInfoDf)+","
  1745. logger.info(fileName+"#"+"解析贷款数据完成")
  1746. logger.info(fileName+"#"+"解析贷记卡数据开始")
  1747. #贷记卡合并df
  1748. creditCardMergeDf = pd.DataFrame(columns=dfParser.dfHeaderCreditCard)
  1749. creditCardPayRecordMergeDf = pd.DataFrame(columns=dfParser.dfHeaderCreditCardPayRecord)
  1750. # logger.info(fileName+"#"+"\033[1;34m +贷记卡信息Dataframe+ \033[0m")
  1751. # logger.info(fileName+"#"+dfParser.dfHeaderCreditCard)
  1752. # 输出数据
  1753. for creditCardDfObj in creditCardAccountDfs:
  1754. creditCardMergeDf = pd.concat([creditCardMergeDf, creditCardDfObj["creditCardDf"]], axis=0, ignore_index=True);
  1755. creditCardPayRecordMergeDf = pd.concat([creditCardPayRecordMergeDf, creditCardDfObj["creditCardPayRecordDf"]], axis=0,ignore_index=True);
  1756. # logger.info(fileName+"#"+creditCardMergeDf.values)
  1757. # 解析贷记卡账户指标
  1758. parseCreditCardMergeDf(creditCardMergeDf);
  1759. parseCreditCardMergeAndPayRecordDf(creditCardMergeDf,creditCardPayRecordMergeDf)
  1760. #准贷记卡合并df
  1761. creditCardMergeDfZ = pd.DataFrame(columns=dfParser.dfHeaderCreditCardZ)
  1762. creditCardPayRecordMergeDfZ = pd.DataFrame(columns=dfParser.dfHeaderCreditCardPayRecordZ)
  1763. for creditCardDfObj in creditCardAccountDfsZ:
  1764. creditCardMergeDfZ = pd.concat([creditCardMergeDfZ, creditCardDfObj["creditCardDfZ"]], axis=0, ignore_index=True);
  1765. creditCardPayRecordMergeDfZ = pd.concat([creditCardPayRecordMergeDfZ, creditCardDfObj["creditCardPayRecordDfZ"]], axis=0,ignore_index=True);
  1766. #解析准贷记卡相关指标
  1767. parseCreditCardMergeDfZ(creditCardMergeDfZ,creditCardPayRecordMergeDfZ);
  1768. logger.info(fileName+"#"+"解析贷记卡数据完成")
  1769. #加工使用率指标
  1770. # result+=("\033[1;34m +贷记卡账户信息+ \033[0m")+","
  1771. result+=utils.toJson(creditCardAccountInfoDf)+","
  1772. result += utils.toJson(creditCardAccountInfoDfZ) + ","
  1773. #使用率
  1774. parseUseRate()
  1775. result += utils.toJson(useRateDf) + ","
  1776. #开户数
  1777. parseOpenAccount(loanMergeDf, creditCardMergeDf, creditCardMergeDfZ,recoveryInfoMergeDf,loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ)
  1778. result += utils.toJson(openAccountDf) + ","
  1779. #24期还款状态
  1780. parsePayRcdStatus(loanMergeDf, creditCardMergeDf, creditCardMergeDfZ,loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ)
  1781. result += utils.toJson(payRcdStatusDf) + ","
  1782. #由于逾期汇总的指标再还款状态之后需要替换占位 TODO
  1783. result = result.replace("briefInfoDf_overdueInfoSum",utils.toJson(briefInfoDf_overdueInfoSum))
  1784. #0525 由于在开户数后,统计信贷信息概要的指标,替换占位符
  1785. result = result.replace("briefInfoDf_loanTradeInfo", utils.toJson(briefInfoDf_loanTradeInfo))
  1786. #公积金
  1787. # 被追偿信息合并df
  1788. housingFundRcdMergeDf = pd.DataFrame(columns=dfParser.dfHeaderHousingFundRcd)
  1789. for housingFundRcdDfObj in housingFundRcdAccountDfs:
  1790. housingFundRcdMergeDf = pd.concat([housingFundRcdMergeDf, housingFundRcdDfObj["housingFundRcdDf"]], axis=0,ignore_index=True);
  1791. parseHousingFundRcd(housingFundRcdMergeDf);
  1792. result += utils.toJson(housingFundRcdDf) + ","
  1793. # result+=("\033[1;34m +查询记录明细+ \033[0m")+","
  1794. result+=utils.toJson(queryRecordDetailDf)+""
  1795. result +="}"
  1796. return result;
  1797. #调用jar包
  1798. def invokePboc(basePath,pdf_path):
  1799. # ===================================
  1800. try:
  1801. # logger.error(pdf_path)
  1802. # fileName = os.path.basename(pdf_path)
  1803. # logger.error(fileName)
  1804. # jsonFileName = fileName.replace("pdf", 'txt')
  1805. businessNum = dbController.getBussinessNum(queryInfo["queryInfoCardId"]); # 根据身份证获取业务编号
  1806. pboc = PBOC(pdf_path.replace("pdf", 'txt'),businessNum)
  1807. jarTxt = pboc.calc();
  1808. result = json.loads(jarTxt)
  1809. logger.info(result)
  1810. if result.get("errcode")== None:
  1811. uploadAudit(result,businessNum)
  1812. else:
  1813. logger.error(result["errmsg"])
  1814. except:
  1815. info = sys.exc_info()
  1816. logger.error(info[0])
  1817. logger.error(info[1])
  1818. # logging.log(logging.ERROR, info[2])
  1819. logger.error(traceback.extract_tb(info[2], 1))
  1820. #上传审批结果
  1821. def uploadAudit(result,businessNum):
  1822. approvalType = result["approveResult"]
  1823. if approvalType=="1":
  1824. approvalOpinion = "征信审批通过"
  1825. approvalType = "4"
  1826. else:
  1827. approvalOpinion = "征信审批失败"
  1828. approvalType = "3"
  1829. taskKey = config.get("baseconf","taskKey")
  1830. appoveApiUrl = config.get("baseconf","appoveApiUrl")
  1831. data = {"header":{
  1832. "ticket": "2938123198320412343",
  1833. "timestamp": int(int(round(time.time() * 1000+60*1000))),
  1834. "nonce": config.get("baseconf", "nonce")
  1835. },
  1836. "body":{"approvalType": approvalType, "businessNum": businessNum,"taskKey":taskKey,"approvalOpinion":approvalOpinion}}
  1837. access_token = dbController.getToken()
  1838. appoveApiUrl = appoveApiUrl+"?access_token="+access_token
  1839. headers = {"Content-Type": "application/json"}
  1840. jsonStr = json.dumps(data);
  1841. jsonStr = jsonStr.replace('"',"\\\"")#必须替换才行
  1842. logger.info(jsonStr)
  1843. pboc = PBOC("","");
  1844. encryData = pboc.encrypt(jsonStr)
  1845. encryData = encryData[0:len(encryData)-2]
  1846. logger.info(encryData)
  1847. response = requests.post(appoveApiUrl, data=encryData,headers=headers)
  1848. text = response.text
  1849. p = PrpCrypt(config.get("baseconf", "AESKey"))
  1850. resultText = p.decrypt(text)
  1851. logger.info(businessNum + "#" + "upload_result:" + resultText)
  1852. def uploadReportResult(basePath,pdf_path):
  1853. # ===================================
  1854. try:
  1855. fileName = os.path.basename(pdf_path)
  1856. #上传文件逻辑
  1857. logger.info(fileName+"#"+fileName+"#"+"准备上传文件")
  1858. uploadApiUrl = config.get("baseconf", "uploadApiUrl");
  1859. uploadApiUrl = uploadApiUrl + "?access_token=" + dbController.getToken()
  1860. files = {'file': open(outPath, 'rb')}
  1861. businessNum = dbController.getBussinessNum(queryInfo["queryInfoCardId"]); # 根据身份证获取业务编号
  1862. logger.info(fileName+"#"+fileName+"#"+"businessNum:"+businessNum)
  1863. logger.info(fileName+"#"+"queryInfoCardId:" + queryInfo["queryInfoCardId"])
  1864. data = {'docType': "23", 'businessNum': businessNum}
  1865. response = requests.post(uploadApiUrl, files=files, data=data)
  1866. text = response.text
  1867. p = PrpCrypt(config.get("baseconf", "AESKey"))
  1868. # logger.info(fileName+"#"+"token:"+token)
  1869. # logger.info(fileName+"#"+url)
  1870. # logger.info(fileName+"#"+result.text)
  1871. resultText = p.decrypt(text)
  1872. logger.info(fileName+"#"+"upload_result:" + resultText)
  1873. descPdfPath = basePath + "execed/" + os.path.basename(pdf_path)
  1874. if not os.path.exists(basePath+"execed/"):
  1875. os.mkdir(basePath+"execed/")
  1876. shutil.move(pdf_path, descPdfPath)
  1877. # shutil.move(pdf_path.replace("pdf","txt"), descPdfPath.replace("pdf","txt"))
  1878. except:
  1879. info = sys.exc_info()
  1880. logger.error(info[0])
  1881. logger.error(info[1])
  1882. # logging.log(logging.ERROR, info[2])
  1883. logger.error(traceback.extract_tb(info[2], 1))
  1884. def updateParseInd(file_name):
  1885. # 检查是否存在已执行
  1886. parseInd = "1"
  1887. try:
  1888. if file_name != "":
  1889. arCert = file_name[0:-4].split("_")
  1890. if len(arCert) == 2:
  1891. cert_id = arCert[1]
  1892. parseIndTmp = dbController.getParseInd(cert_id)
  1893. if parseIndTmp =="1":
  1894. return True
  1895. dbController.updateParseInd(cert_id, parseInd)
  1896. except:
  1897. logger.error("update parse ind error")
  1898. return False
  1899. # grouped.to_csv(r'C:\Users\Mortal\Desktop\ex.csv',index=False, encoding='utf_8_sig')
  1900. if __name__ == '__main__':
  1901. file_name = ""
  1902. # basePath = "D:/mydocument/myproject/git/busscredit/20200414_report/";
  1903. basePath = "D:/mydocument/myprojects/creditreport/parse/"
  1904. basePath = "Z:/cr/parse/"
  1905. # file_name = "周颖500108199002111229.pdf"#准贷记卡已销户 呆账
  1906. # file_name = "王思13052819911012122X.pdf"#公积金
  1907. # file_name = "杨夏龙440902198410014270.pdf"#转出
  1908. # file_name = "翟彦超230125199004174216.pdf"#准贷记卡 呆账
  1909. # file_name = "蔡月辉330326198502116146.pdf" # 配偶
  1910. # file_name = "周芳芳342501198706111782.pdf" #被追偿信息
  1911. # file_name = "付春雁533001198507220344.pdf" # 公积金记录
  1912. # pdf_path = basePath + "陈洁350122199005027726.pdf" # 相关还款责任
  1913. # file_name = "叶翔_330126197005200077.pdf" # 准贷记卡分页
  1914. file_name = "安静513723198707074647.pdf" #
  1915. file_name = "姚钧_120101198903033539.pdf" #
  1916. pdf_path = basePath + file_name
  1917. if len(sys.argv)>1:
  1918. basePath = sys.argv[1]
  1919. pdf_path = basePath + sys.argv[2]
  1920. file_name = sys.argv[2]
  1921. # print(sys.argv)
  1922. isBat = False#批量的有问题
  1923. isPlt = config.get("baseconf", "isPlt");
  1924. if isBat:#批量生成数据不对
  1925. for file in os.listdir(basePath):
  1926. if file.endswith("pdf"):
  1927. start = timeit.default_timer();
  1928. pdf_path = basePath+file;
  1929. outPath = pdf_path.replace("pdf",'txt')
  1930. if os.path.exists(outPath):
  1931. continue;
  1932. logger.info(file + "解析开始...")
  1933. try:
  1934. result = main(pdf_path)
  1935. except:
  1936. info = sys.exc_info()
  1937. logger.error(info[0])
  1938. logger.error( info[1])
  1939. # logging.log(logging.ERROR, info[2])
  1940. logger.error(traceback.extract_tb(info[2], 1))
  1941. # print(result)
  1942. #输出到文件
  1943. sys.stdout = open(outPath, mode='w', encoding='utf-8')
  1944. print(result.replace("\033[1;34m","").replace("\033[0m",""))
  1945. logger.info(file+"解析完成")
  1946. gc.collect()
  1947. s = timeit.default_timer() - start;
  1948. logger.info(str(s) + " 秒")
  1949. else:
  1950. if pdf_path.endswith("pdf"):
  1951. start = timeit.default_timer();
  1952. outPath = pdf_path.replace("pdf", 'txt')
  1953. result = ""
  1954. if isPlt == "1":#生产模式
  1955. if not os.path.exists(outPath):#不存在才生成
  1956. try:
  1957. isExec = updateParseInd(file_name)
  1958. if not isExec:#没有在执行
  1959. logger.info(file_name + "解析开始...")
  1960. result = main(pdf_path)
  1961. sys.stdout = open(outPath, mode='w', encoding='utf-8')
  1962. print(result.replace("\033[1;34m", "").replace("\033[0m", ""))
  1963. logger.info(file_name + "解析完成")
  1964. s = timeit.default_timer() - start;
  1965. logger.info(file_name+"#"+str(s) + " 秒")
  1966. uploadReportResult(basePath,pdf_path);
  1967. #调用jar计算审批结果
  1968. invokePboc(basePath, pdf_path);
  1969. except:
  1970. info = sys.exc_info()
  1971. logger.error(file_name+"#"+"解析失败")
  1972. logger.error(info[0])
  1973. logger.error(info[1])
  1974. logger.error(traceback.extract_tb(info[2]))
  1975. else:
  1976. isExec = updateParseInd(file_name)
  1977. if not isExec: # 没有在执行
  1978. result = main(pdf_path)
  1979. sys.stdout = open(outPath, mode='w', encoding='utf-8')
  1980. print(result.replace("\033[1;34m", "").replace("\033[0m", ""))
  1981. logger.info(file_name + "解析完成")
  1982. s = timeit.default_timer() - start;
  1983. logger.info(file_name+"#"+str(s) + " 秒")
  1984. # uploadReportResult(basePath,pdf_path);
  1985. # 调用jar计算审批结果
  1986. invokePboc(basePath, pdf_path);