Commit a22d18be by 黄静

hj

parent 7bb854ad
# coding:utf-8 # coding:utf-8
import traceback #计算风控结果
from IndexItem import IndexItem
import json
import re import re
class IndexComputer: class IndexComputer:
funs=[]#公式集合 funs=[]#公式集合
def Init(self): def Init(self):
return "" return ""
def Compute(self,indexItem):#计算单一指标 def Compute(self,indexItem):#计算单一指标
#如果所有因子有一个为空,返回数据不存在 # 如果所有因子有一个为空,返回数据不存在
i=0 i = 0
X=[] X = []
Y=[] Y = []
V={} V = {}
S=[] S = []
print(indexItem.Name)
print(indexItem.Funs)
print(indexItem.FactorsValue)
for factorkey in indexItem.FactorsValue: for factorkey in indexItem.FactorsValue:
tempval=indexItem.FactorsValue[factorkey] tempval = indexItem.FactorsValue[factorkey]
if indexItem.FactorsValue[factorkey] is None: if indexItem.FactorsValue[factorkey] is None:
print("is None") print("is None")
return "0" return "0"
...@@ -28,24 +24,22 @@ class IndexComputer: ...@@ -28,24 +24,22 @@ class IndexComputer:
except: except:
print("is isNumeric", indexItem.FactorsValue[factorkey]) print("is isNumeric", indexItem.FactorsValue[factorkey])
return "0" return "0"
Y.append(float(indexItem.FactorsValue[factorkey])) Y.append(float(indexItem.FactorsValue[factorkey]))
V[factorkey]=str("Y["+str(i)+"]") V[factorkey] = str("Y[" + str(i) + "]")
S.append(factorkey) S.append(factorkey)
i=i+1 i = i + 1
S = sorted(S, key=lambda i: len(i), reverse=True)
#print(Y,V) j = 0
S=sorted(S, key=lambda i: len(i), reverse=True)
# print(S)
j=0
for fun in indexItem.Funs: for fun in indexItem.Funs:
funstr=fun print(indexItem.id,"===============gsid")
funstr = fun
for s in S: for s in S:
funstr=funstr.replace(s,str(V[s])) funstr = funstr.replace(s, str(V[s]))
strinfo = re.compile(r'X\[\d*\]=') strinfo = re.compile(r'X\[\d*\]=')
funstr = strinfo.sub("", funstr) funstr = strinfo.sub("", funstr)
#funstr=funstr.replace("/X[d]=/","") # funstr=funstr.replace("/X[d]=/","")
try: try:
print(funstr,"======funstr")
val = eval(funstr) val = eval(funstr)
X.append(val) X.append(val)
j = j + 1 j = j + 1
...@@ -53,7 +47,7 @@ class IndexComputer: ...@@ -53,7 +47,7 @@ class IndexComputer:
print('Handling run-time error:', err) print('Handling run-time error:', err)
return "0" return "0"
except(ValueError): except(ValueError):
print('other:',ValueError) print('other:', ValueError)
return "0" return "0"
# try: # try:
...@@ -61,5 +55,48 @@ class IndexComputer: ...@@ -61,5 +55,48 @@ class IndexComputer:
return "2" return "2"
else: else:
return "1" return "1"
# except:
# return "0" def finance_Compute(self, indexItem):
\ No newline at end of file finance_result = {}
i = 0
X = []
Y = []
V = {}
S = []
for factorkey in indexItem.FactorsValue:
tempval = indexItem.FactorsValue[factorkey]
if type(tempval) == str:
eval(tempval)
else:
tempval = tempval
Y.append(float(indexItem.FactorsValue[factorkey]))
V[factorkey] = str("Y[" + str(i) + "]")
S.append(factorkey)
i = i + 1
S = sorted(S, key=lambda i: len(i), reverse=True)
j = 0
for fun in indexItem.Funs:
funstr = fun
for s in S:
funstr = funstr.replace(s, str(V[s]))
strinfo = re.compile(r'X\[\d*\]=')
funstr = strinfo.sub("", funstr)
try:
if type(funstr) == str:
val = eval(funstr)
else:
val = funstr
X.append(val)
j = j + 1
except ZeroDivisionError as err:
print('finance error:', err)
return "∞"
except(ValueError):
print('other:', ValueError)
return "—"
Finance_result = int(X[j - 1])
if Finance_result ==0.0:
Finance_result= int(Finance_result)
else:
Finance_result=Finance_result
return Finance_result
\ No newline at end of file
...@@ -17,18 +17,21 @@ FK_DB_NAME = env_dist.get('FK_DB_NAME') #获取mysql库 ...@@ -17,18 +17,21 @@ FK_DB_NAME = env_dist.get('FK_DB_NAME') #获取mysql库
class IndexGet: class IndexGet:
conn = pymysql.connect(host=FK_DB_HOST,port=int(FK_DB_PORT),user=FK_DB_USER,password=FK_DB_PWD,db=FK_DB_NAME,charset="utf8mb4") conn = pymysql.connect(host=FK_DB_HOST,port=int(FK_DB_PORT),user=FK_DB_USER,password=FK_DB_PWD,db=FK_DB_NAME,charset="utf8mb4")
def Subscribe(self,span,type): # conn = pymysql.connect(host='47.105.186.2',port=3307,user='caishui',password='jvmfTVDuG5YE(*Z',db='fktaxctl',charset="utf8mb4")
print("查询条件",span,type) #检索财税03的情况:
def Subscribe(self,span,company_type):
cursor = self.conn.cursor() cursor = self.conn.cursor()
list = [] list = []
sql = "SELECT * from gongshi WHERE span = %s and type = %s;" sql = "SELECT * from gongshi2 WHERE span = %s and vat_type = %s order by indexName;"
try: try:
# 执行SQL语句 # 执行SQL语句
cursor.execute(sql,[span,type]) cursor.execute(sql,[span,company_type])
# 获取所有记录列表 # 获取所有记录列表
results = cursor.fetchall() results = cursor.fetchall()
# for row in results[1:2]:
for row in results: for row in results:
indexItem=IndexItem() indexItem=IndexItem()
indexItem.id = row[0]
indexItem.Name = row[1] indexItem.Name = row[1]
indexItem.IndexName = row[2] indexItem.IndexName = row[2]
funs = str(row[3]) funs = str(row[3])
...@@ -40,9 +43,10 @@ class IndexGet: ...@@ -40,9 +43,10 @@ class IndexGet:
for fun in funs: for fun in funs:
funsGrp.append(fun) funsGrp.append(fun)
indexItem.Funs=funsGrp indexItem.Funs=funsGrp
indexItem.Factors = row[4]
indexItem.Span = row[5] indexItem.Span = row[5]
indexItem.Factors=row[4]
indexItem.Type = row[6] indexItem.Type = row[6]
indexItem.Category = row[8]
list.append(indexItem) list.append(indexItem)
except: except:
print("Error: unable to fetch data") print("Error: unable to fetch data")
......
...@@ -7,6 +7,4 @@ class IndexItem: ...@@ -7,6 +7,4 @@ class IndexItem:
FactorsValue={} FactorsValue={}
Span="" Span=""
Type="" Type=""
Description="" Description=""
\ No newline at end of file
...@@ -12,14 +12,16 @@ FK_DB_NAME = env_dist.get('FK_DB_NAME') #获取mysql库 ...@@ -12,14 +12,16 @@ FK_DB_NAME = env_dist.get('FK_DB_NAME') #获取mysql库
class RiskComputer: class RiskComputer:
IndexRes={} IndexRes={}
IndexRes1={}
indexs=[] indexs=[]
RCFactorsValue={} RCFactorsValue={}
# batch_No=0
def IndexsGet(self,indexs): def IndexsGet(self,indexs):
self.indexs=indexs self.indexs=indexs
def FactorGet(self,factors): def FactorGet(self,factors):
self.RCFactorsValue=factors self.RCFactorsValue=factors
def Compute(self):#计算所有指标 def Compute(self,Previous_Date):#计算所有指标
Curr_Date = Previous_Date['Curr_Date']
Previous_Date = Previous_Date['Previous_Date']
for indexItem in self.indexs: for indexItem in self.indexs:
factors=indexItem.Factors.split(":") factors=indexItem.Factors.split(":")
flag=True flag=True
...@@ -30,30 +32,61 @@ class RiskComputer: ...@@ -30,30 +32,61 @@ class RiskComputer:
else: else:
flag=False flag=False
break break
if flag: ic=IndexComputer()
ic=IndexComputer() if indexItem.Category == 'tax_risk':
ret=ic.Compute(indexItem) if flag:
self.IndexRes[indexItem.Name]=ret ret=ic.Compute(indexItem)
self.IndexRes[indexItem.Name]=ret
else:
self.IndexRes[indexItem.Name]="0"
else: else:
self.IndexRes[indexItem.Name]="0" if flag:
ret = ic.finance_Compute(indexItem)
else:
ret = "—"
a=indexItem.Name
if(a not in self.IndexRes1):
self.IndexRes1[a]={Curr_Date:ret}
else:
if(Previous_Date not in self.IndexRes1[a]):
self.IndexRes1[a][Previous_Date]=ret
else:
self.IndexRes1[a]["change_rate"]=ret
def Ret2Json(self):#把指标结果转化为樊辉需要的Json def Ret2Json(self):#把指标结果转化为樊辉需要的Json
#json写入数据库 #json写入数据库
# db = pymysql.connect(host='47.105.186.2',port=3307,user='caishui',password='jvmfTVDuG5YE(*Z',db='fktaxctl',charset="utf8mb4")
db = pymysql.connect(host=FK_DB_HOST,port=int(FK_DB_PORT),user=FK_DB_USER,password=FK_DB_PWD,db=FK_DB_NAME,charset="utf8mb4") db = pymysql.connect(host=FK_DB_HOST,port=int(FK_DB_PORT),user=FK_DB_USER,password=FK_DB_PWD,db=FK_DB_NAME,charset="utf8mb4")
cursor = db.cursor() cursor = db.cursor()
for key in self.IndexRes: arr = [self.IndexRes,self.IndexRes1]
sql = """INSERT INTO result_set(batchno,indexName,status) VALUES ('"""+str(self.batch_No)+"""', '"""+str(key)+"""','"""+str(self.IndexRes[key])+"""')""" ss = ['ri','fi']
try: for i,index_results in enumerate(arr): #索引,值
cursor.execute(sql) print(i,"=============i")
# 提交到数据库执行 print(index_results, "=============qq")
db.commit() for key in index_results:
except: # print(self.indexs['id'],"=======公式id")
db.rollback() #'factors_name':'指标状态'
ri1 = {}
# 关闭数据库连接 ri1[key]= index_results[key]
insert_batch_No = "'"+str(self.batch_No)+"'"
fi_dict={"营业总收入":"Total_trade_income","利润总额":"Total_profit","净利润":"Net_profit","负债总额":"Total_Liabilities","所有人权益":"Owner_rights","销售总额":"Total_sales",
"资产总额":"Total_assets","负债及所有者权益合计":"Total_liabilities_and_Owner_rights","销售费用":"sales_expense","销售净利率":"Net_interest_rate","产权比率":"Equity_ratio",
"销售增长率":"sales_growth_rate","净利润增长率":"Net_profit_growth_rate","资产负债比率":"Gearing_ratio","总资产增长率":"total_assets_growth_rate"
}
if key in fi_dict:
insert_key = str(fi_dict[key])
else:
insert_key = str(key)
insert_status = str(index_results[key])
sql='INSERT INTO result_set(Batchno,indexName,status,biztype) VALUES (%s,"%s","%s","%s")'%(insert_batch_No,insert_key,insert_status,ss[i])
# print(sql,"======风控sql")
try:
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except Exception as e:
print(e)
db.rollback()
# 关闭数据库连接
db.close() db.close()
jsonStr=json.dumps(self.IndexRes,ensure_ascii=False, indent=4, separators=(',', ':')) jsonStr=json.dumps(self.IndexRes1,ensure_ascii=False, indent=4, separators=(',', ':'))
# #写入信息到Redis的队列中
# redisPool = redis.ConnectionPool(host=FK_REDIS_HOST, port=8967, password='Gongsibao2018',db=2)
# client = redis.Redis(connection_pool=redisPool)
# client.lpush('funcmq','{"key":'+str(datetime.datetime.now())+',"content":'+str(self.batch_No)+'}')
return jsonStr return jsonStr
\ No newline at end of file
...@@ -13,6 +13,7 @@ FK_DB_PWD = env_dist.get('FK_DB_PWD') #获取mysql密码 ...@@ -13,6 +13,7 @@ FK_DB_PWD = env_dist.get('FK_DB_PWD') #获取mysql密码
FK_DB_NAME = env_dist.get('FK_DB_NAME') #获取mysql库 FK_DB_NAME = env_dist.get('FK_DB_NAME') #获取mysql库
class UpdateId: class UpdateId:
conn = pymysql.connect(host=FK_DB_HOST,port=int(FK_DB_PORT),user=FK_DB_USER,password=FK_DB_PWD,db=FK_DB_NAME,charset="utf8mb4") conn = pymysql.connect(host=FK_DB_HOST,port=int(FK_DB_PORT),user=FK_DB_USER,password=FK_DB_PWD,db=FK_DB_NAME,charset="utf8mb4")
# conn = pymysql.connect(host='47.105.186.2', port=3307, user='caishui', password='jvmfTVDuG5YE(*Z', db='fktaxctl',charset="utf8mb4")
def Update(self,BatchNo): def Update(self,BatchNo):
cursor = self.conn.cursor() cursor = self.conn.cursor()
sql = "UPDATE upload_batch SET batchstatuscode = 'rptover' WHERE id = %s;" sql = "UPDATE upload_batch SET batchstatuscode = 'rptover' WHERE id = %s;"
......
安装环境:3.7.2
安装包:pip install redis
pip install pymysql
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment