Commit a22d18be by 黄静

hj

parent 7bb854ad
# coding:utf-8
import traceback
from IndexItem import IndexItem
import json
#计算风控结果
import re
class IndexComputer:
funs=[]#公式集合
def Init(self):
return ""
def Compute(self,indexItem):#计算单一指标
#如果所有因子有一个为空,返回数据不存在
i=0
X=[]
Y=[]
V={}
S=[]
print(indexItem.Name)
print(indexItem.Funs)
print(indexItem.FactorsValue)
# 如果所有因子有一个为空,返回数据不存在
i = 0
X = []
Y = []
V = {}
S = []
for factorkey in indexItem.FactorsValue:
tempval=indexItem.FactorsValue[factorkey]
tempval = indexItem.FactorsValue[factorkey]
if indexItem.FactorsValue[factorkey] is None:
print("is None")
return "0"
......@@ -28,24 +24,22 @@ class IndexComputer:
except:
print("is isNumeric", indexItem.FactorsValue[factorkey])
return "0"
Y.append(float(indexItem.FactorsValue[factorkey]))
V[factorkey]=str("Y["+str(i)+"]")
V[factorkey] = str("Y[" + str(i) + "]")
S.append(factorkey)
i=i+1
#print(Y,V)
S=sorted(S, key=lambda i: len(i), reverse=True)
# print(S)
j=0
i = i + 1
S = sorted(S, key=lambda i: len(i), reverse=True)
j = 0
for fun in indexItem.Funs:
funstr=fun
print(indexItem.id,"===============gsid")
funstr = fun
for s in S:
funstr=funstr.replace(s,str(V[s]))
funstr = funstr.replace(s, str(V[s]))
strinfo = re.compile(r'X\[\d*\]=')
funstr = strinfo.sub("", funstr)
#funstr=funstr.replace("/X[d]=/","")
# funstr=funstr.replace("/X[d]=/","")
try:
print(funstr,"======funstr")
val = eval(funstr)
X.append(val)
j = j + 1
......@@ -53,7 +47,7 @@ class IndexComputer:
print('Handling run-time error:', err)
return "0"
except(ValueError):
print('other:',ValueError)
print('other:', ValueError)
return "0"
# try:
......@@ -61,5 +55,48 @@ class IndexComputer:
return "2"
else:
return "1"
# except:
# return "0"
\ No newline at end of file
def finance_Compute(self, indexItem):
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库
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")
def Subscribe(self,span,type):
print("查询条件",span,type)
# conn = pymysql.connect(host='47.105.186.2',port=3307,user='caishui',password='jvmfTVDuG5YE(*Z',db='fktaxctl',charset="utf8mb4")
#检索财税03的情况:
def Subscribe(self,span,company_type):
cursor = self.conn.cursor()
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:
# 执行SQL语句
cursor.execute(sql,[span,type])
cursor.execute(sql,[span,company_type])
# 获取所有记录列表
results = cursor.fetchall()
# for row in results[1:2]:
for row in results:
indexItem=IndexItem()
indexItem.id = row[0]
indexItem.Name = row[1]
indexItem.IndexName = row[2]
funs = str(row[3])
......@@ -40,9 +43,10 @@ class IndexGet:
for fun in funs:
funsGrp.append(fun)
indexItem.Funs=funsGrp
indexItem.Factors = row[4]
indexItem.Span = row[5]
indexItem.Factors=row[4]
indexItem.Type = row[6]
indexItem.Category = row[8]
list.append(indexItem)
except:
print("Error: unable to fetch data")
......
......@@ -7,6 +7,4 @@ class IndexItem:
FactorsValue={}
Span=""
Type=""
Description=""
Description=""
\ No newline at end of file
......@@ -12,14 +12,16 @@ FK_DB_NAME = env_dist.get('FK_DB_NAME') #获取mysql库
class RiskComputer:
IndexRes={}
IndexRes1={}
indexs=[]
RCFactorsValue={}
# batch_No=0
def IndexsGet(self,indexs):
self.indexs=indexs
def FactorGet(self,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:
factors=indexItem.Factors.split(":")
flag=True
......@@ -30,30 +32,61 @@ class RiskComputer:
else:
flag=False
break
if flag:
ic=IndexComputer()
ret=ic.Compute(indexItem)
self.IndexRes[indexItem.Name]=ret
ic=IndexComputer()
if indexItem.Category == 'tax_risk':
if flag:
ret=ic.Compute(indexItem)
self.IndexRes[indexItem.Name]=ret
else:
self.IndexRes[indexItem.Name]="0"
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
#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")
cursor = db.cursor()
for key in self.IndexRes:
sql = """INSERT INTO result_set(batchno,indexName,status) VALUES ('"""+str(self.batch_No)+"""', '"""+str(key)+"""','"""+str(self.IndexRes[key])+"""')"""
try:
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
db.rollback()
# 关闭数据库连接
cursor = db.cursor()
arr = [self.IndexRes,self.IndexRes1]
ss = ['ri','fi']
for i,index_results in enumerate(arr): #索引,值
print(i,"=============i")
print(index_results, "=============qq")
for key in index_results:
# print(self.indexs['id'],"=======公式id")
#'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()
jsonStr=json.dumps(self.IndexRes,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)+'}')
jsonStr=json.dumps(self.IndexRes1,ensure_ascii=False, indent=4, separators=(',', ':'))
return jsonStr
\ No newline at end of file
......@@ -13,6 +13,7 @@ FK_DB_PWD = env_dist.get('FK_DB_PWD') #获取mysql密码
FK_DB_NAME = env_dist.get('FK_DB_NAME') #获取mysql库
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='47.105.186.2', port=3307, user='caishui', password='jvmfTVDuG5YE(*Z', db='fktaxctl',charset="utf8mb4")
def Update(self,BatchNo):
cursor = self.conn.cursor()
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