Commit 1e17b486 by huangjing

hj

parent aac893e9
# 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)
for factorkey in indexItem.FactorsValue:
tempval=indexItem.FactorsValue[factorkey]
if indexItem.FactorsValue[factorkey] is None:
print("is None")
return "0"
try:
eval(tempval)
except:
print("is isNumeric", indexItem.FactorsValue[factorkey])
return "0"
Y.append(float(indexItem.FactorsValue[factorkey]))
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
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)
#funstr=funstr.replace("/X[d]=/","")
try:
val = eval(funstr)
X.append(val)
j = j + 1
except ZeroDivisionError as err:
print('Handling run-time error:', err)
return "0"
except(ValueError):
print('other:',ValueError)
return "0"
# try:
if X[j - 1] == True:
return "2"
else:
return "1"
# except:
# return "0"
\ No newline at end of file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/12/29 0029 下午 3:01
# @Author : hj
# @File : IndexGet.py
# @Software: PyCharm
import pymysql
from IndexItem import IndexItem
class IndexGet:
conn = pymysql.connect(host='43.247.184.35',port=8899,user='write',password='write',db='fktaxctl',charset="utf8mb4")
def Subscribe(self,span,type):
cursor = self.conn.cursor()
list = []
sql = "SELECT * from gongshi WHERE span = %s and type = %s;"
try:
# 执行SQL语句
cursor.execute(sql,[span,type])
print("查询条件",span,type)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
indexItem=IndexItem()
# indexItem.Id = row[0]
indexItem.Name = row[1]
indexItem.IndexName = row[2]
funs=str(row[3]).replace("\n","").split(";")
funsGrp=[]
for fun in funs:
funsGrp.append(fun)
indexItem.Funs=funsGrp
indexItem.Span = row[5]
indexItem.Factors=row[4]
indexItem.Type = row[6]
list.append(indexItem)
except:
print("Error: unable to fetch data")
return ("Error: unable to fetch data")
finally:
cursor.close()
return list
def close(self):
self.conn.close()
\ No newline at end of file
# coding:utf-8
class IndexItem:
Name=""
IndexName=""
Funs=[]
Factors=""
FactorsValue={}
Span=""
Type=""
Description=""
# coding:utf-8
from IndexItem import IndexItem
from IndexComputerFile import IndexComputer
import json,redis,datetime,pymysql
class RiskComputer:
IndexRes={}
indexs=[]
RCFactorsValue={}
# batch_No=0
def IndexsGet(self,indexs):
self.indexs=indexs
def FactorGet(self,factors):
self.RCFactorsValue=factors
def Compute(self):#计算所有指标
for indexItem in self.indexs:
factors=indexItem.Factors.split(":")
flag=True
indexItem.FactorsValue={}
for factor in factors:
if factor in self.RCFactorsValue:
indexItem.FactorsValue[factor]=self.RCFactorsValue[factor]
else:
flag=False
break
if flag:
ic=IndexComputer()
ret=ic.Compute(indexItem)
self.IndexRes[indexItem.Name]=ret
else:
self.IndexRes[indexItem.Name]="0"
def Ret2Json(self):#把指标结果转化为樊辉需要的Json
#json写入数据库
db = pymysql.connect(host='43.247.184.35',port=8899,user='write',password='write',db='fktaxctl',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()
# 关闭数据库连接
db.close()
jsonStr=json.dumps(self.IndexRes,ensure_ascii=False, indent=4, separators=(',', ':'))
#写入信息到Redis的队列中
redisPool = redis.ConnectionPool(host='43.247.184.32', 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
\ No newline at end of file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/1/1 0001 下午 3:31
# @Author : hj
# @File : getInfoByBatchNo.py
# @Software: PyCharm
import requests,json,redis,re
from RiskComputer import RiskComputer
from FactorGet import FactorGet
from IndexGet import IndexGet
#使用任务号获取任务信息
def getInfo_ByBatchNo(BatchNo):
Info_task=[]
url = 'http://47.94.0.45:9011/risk-api/getInfoByBatchNo' #获取信息接口
name = {"batchCode":BatchNo} # 根据任务号进行接口访问参数
taskInfo = requests.get(url,name) # 访问接口返回的信息
taskInfo_New = json.loads(taskInfo.text)
print("任务信息获取:",taskInfo_New)
if taskInfo_New['data'] is None:
print("taskInfo_New['data'] is None")
quit()
Info_Task = taskInfo_New['data']
AccountInfo = {}
AccountInfo["taxCode"]=Info_Task['taxCode'] # 获取纳税人识别号
AccountInfo["batchCode"]=Info_Task['batchCode'] # 获取批次号
AccountInfo["timeType"] = Info_Task['timeType'] # 获取时间类型
if Info_Task["timeType"] =="Y":
currentIssue = Info_Task["checkYear"]
elif Info_Task["timeType"] =="Q":
currentIssue = Info_Task["checkQuarter"]
else:currentIssue = Info_Task["checkMonth"]
AccountInfo["currentIssue"]=currentIssue
Info_task.append(AccountInfo)
print("返回任务信息")
return Info_task
# 任务信息: [{'taxCode': '123456', 'batchCode': '51', 'timeType': 'Y', 'currentIssue': '2019'}]
#获取自定义的期数
def customBatch(custom_currentIssue,offset,timeType):
url = 'http://47.94.0.45:9011/risk-api/getIssueByCustomer' #获取信息接口
name = {"currentIssue":custom_currentIssue,"offset":offset,"timeType":timeType} # 接口访问参数
batchInfo = requests.post(url,name) # 访问接口返回的信息
batchInfo_New = json.loads(batchInfo.text)
currentIssue = batchInfo_New['data']
print("接口计算的期数为:",currentIssue)
return currentIssue
#获取L期数信息
def Transformer(currentYear,YearyearInfo,issueNum):
currentIssue=""
year=0
if "L" in YearyearInfo:
year=currentYear-1
else:
year=currentYear
if "Q" in YearyearInfo:
issueNumTemp=int(issueNum)*3
issueNumStr=str(issueNumTemp)
if(len(str(issueNumTemp)))<2:
issueNumStr="0"+str(issueNumTemp)
currentIssue=str(year)+issueNumStr
else:
if(len(issueNum))<2:
issueNum="0"+str(issueNum)
currentIssue=str(year)+str(issueNum)
print("自己计算期数为:",currentIssue)
return currentIssue
#获取本期指定报表的单元格值
def getValue(batchCode,cellPos,currentIssue,fileCode,taxCode,timeType):
batchCode = str(batchCode)
cellPos =str(cellPos)
currentIssue =str(currentIssue)
fileCode = str(fileCode)
taxCode = str(taxCode)
timeType =str(timeType)
url = 'http://47.94.0.45:9011/risk-api/getCellValuesByIssue' #获取信息接口
name = {"batchCode":batchCode,"cellPos":cellPos,"currentIssue":currentIssue,"fileCode":fileCode,"taxCode":taxCode,"timeType":timeType} # 接口访问参数
contentInfo = requests.post(url,name) # 访问接口返回的信息
batchInfo_New = json.loads(contentInfo.text)
index_Values = batchInfo_New['data']
if index_Values is None:
index_Value =0 #"缺少数据"
else:
index = index_Values[0]
index_Value = index["cellContent"]
print("单元格数据为:",index_Value)
return index_Value
def fun(str):
print(str,"ooo")
fun_list=[]
indexdict={}
if len(str.split("_")[3])<=2 :
str=str+'0'
table=str.split("_")[0]
row=str.split("_")[1]
cloumn=str.split("_")[2]
times=str.split("_")[3]
nums=re.findall(r'([A-Z]+)([0-9]+)',times)[0][1]
indexdict["table"]=table
indexdict["row"] = row
indexdict["cloumn"]= cloumn
indexdict["times"] = times
indexdict["nums"] = "-"+nums
indexdict["issueNum"] = nums
fun_list.append(indexdict)
return fun_list
redisPool = redis.ConnectionPool(host='43.247.184.32', port=8967, password='Gongsibao2018',db=2)
client = redis.Redis(connection_pool=redisPool)
# value=client.rpop('notifyRule')
a = client.lrange('notifyRule',0,1)
value =a[0]
if client is None:
quit()
if value is None:
quit()
result=json.loads(value)
content=result["content"]
taxTypeCode=content['taxTypeCode']#企业性质
accountTypeCode=content['accountTypeCode']#会计准则
BatchNo=content["batchCode"]
# taxTypeCode="ST"#企业性质
# accountTypeCode="S"#会计准则
# BatchNo=51
if taxTypeCode=="ST":
taxTypeCode="S"
else:
taxTypeCode="G"
type=taxTypeCode+"-"+accountTypeCode
indexsGet=IndexGet()#获取所有指标和所有因子
#根据任务号获取任务信息
Info_task=getInfo_ByBatchNo(BatchNo)
tasks=Info_task[0]
indexs=indexsGet.Subscribe(tasks['timeType'],type)#根据时间类型和企业类型获取特征s
factors={}
for indexItem in indexs:
factorsStr=indexItem.Factors
# print(factorsStr)
factorsGrp=factorsStr.replace(":",":").split(":")
for factorItem in factorsGrp:
if factorItem not in factors and len(factorItem.lstrip().rstrip())>0:
factors[factorItem]=0.0
factorsnew={}
for factor in factors:#获取所有因子
fun_list=fun(str(factor))
index=fun_list[0]
batchCode = BatchNo
cellPos = index['row'] + "-" +index['cloumn']
offset = index['nums']
times = index['times']
issueNum = index['issueNum']
YearyearInfo = times[0:2]
currentIssue = tasks["currentIssue"]
fileCode = index['table']
taxCode = tasks["taxCode"]
timeType = tasks["timeType"]
currentYear = int(currentIssue[0:4])
#获取任务信息
indexsGet = IndexGet() # 获取所有指标和所有因子
# 获取L期数信息
Info_LBatch=0
if "L" in YearyearInfo:
Info_LBatch = Transformer(currentYear, YearyearInfo, issueNum)
else:
# 获取自定义期数
Info_LBatch=customBatch(currentIssue,offset,timeType)
# 获取单元格值
index_Value = getValue(batchCode,cellPos,Info_LBatch,fileCode,taxCode,timeType)
factorsnew[factor] = index_Value
# print(index_Value)
factors=factorsnew
rc=RiskComputer() #构建指标计算对象
rc.batch_No =batchCode
rc.FactorGet(factors)#把因子装入对象
rc.IndexsGet(indexs)#把指标装入对象
rc.Compute()#指标计算
jsonstr = rc.Ret2Json()#指标输出成樊辉要的格式
print(jsonstr)
# client.rpop('notifyRule')
\ No newline at end of file
{
"lockfileVersion": 1
}
安装环境: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