Ejemplo n.º 1
0
    def send(url, data, appid, sign, accesstoken=''):
        utctime = datetime.datetime.utcnow()
        timestamp = utctime.strftime('%Y-%m-%d %H:%M:%S')
        headers = {
            "X-PPD-APPID": appid,
            "X-PPD-SIGN": sign,
            "X-PPD-TIMESTAMP": timestamp,
            "X-PPD-TIMESTAMP-SIGN": rsa.sign("%s%s" % (appid, timestamp)),
            "Accept": "application/json;charset=UTF-8"
        }
        if accesstoken.strip():
            headers["X-PPD-ACCESSTOKEN"] = accesstoken
        status_code, response_str = http_client.http_post(url,
                                                          data.encode('utf-8'),
                                                          headers=headers)

        retry_count = 0
        while status_code != 200:
            logging.warning("Service unavailable for a while.")
            retry_count = retry_count + 1
            time.sleep(1)
            if retry_count > 3:
                logging.error(
                    "Service failed. Please wait a moment and retry.")
                # catch this at user code to wait for a reasonable long time
                raise RuntimeError("Wow, requests are sent too frequently...")
            status_code, response_str = http_client.http_post(
                url, data.encode('utf-8'), headers=headers)

        return response_str
Ejemplo n.º 2
0
def get_user_fund_balance(appid, access_token):
    #获取用户资金余额
    access_url = "http://gw.open.ppdai.com/balance/balanceService/QueryBalance"
    data = {}
    sort_data = rsa.sort(data)
    sign = rsa.sign(sort_data)
    list_result = client.send(access_url,json.dumps(data) , appid, sign,access_token)
Ejemplo n.º 3
0
 def getBalance(self):
     access_url = "https://openapi.ppdai.com/balance/balanceService/QueryBalance"
     data = {}
     sort_data = rsa.sort(data)
     sign = rsa.sign(sort_data)
     list_result = client.send(access_url, json.dumps(data), appid, sign, self.token)
     self.balance = list_result["Balance"][0]["Balance"]
     log("balance end",self.balance)
     return self.balance
Ejemplo n.º 4
0
def get_batch_listing_infos(appid, data):
    #新版散标详情批量接口(请求列表不大于10)
    utctime = datetime.datetime.utcnow()
    #data = {"timestamp":utctime.strftime('%Y-%m-%d %H:%M:%S')}#time.strftime('%Y-%m-%d %H:%M:%S',)

    access_url = "http://gw.open.ppdai.com/invest/LLoanInfoService/BatchListingInfos"
    sort_data = rsa.sort(data)
    sign = rsa.sign(sort_data)
    list_result = client.send(access_url, json.dumps(data) , appid, sign)
Ejemplo n.º 5
0
def get_listingids(appid, access_token):
    #获得投标标的
    access_url = "http://gw.open.ppdai.com/invest/LLoanInfoService/LoanList"
    data = {
      "PageIndex": 3, 
      "StartDateTime": "2015-11-11 12:00:00.000"
    }
    sort_data = rsa.sort(data)
    sign = rsa.sign(sort_data)
    list_result = client.send(access_url,json.dumps(data) , appid, sign)
Ejemplo n.º 6
0
def getListingIdInfo(ListingIds):
    access_url = "https://openapi.ppdai.com/listing/openapiNoAuth/batchListingInfo"

    data = {
        "ListingIds": ListingIds
    }
    sort_data = rsa.sort(data)
    sign = rsa.sign(sort_data)
    list_result = client.send(access_url, json.dumps(data) , appid, sign)
    if (list_result["Result"] != 1):
        log("error getListingIdInfo")
    return list_result["LoanInfos"] 
Ejemplo n.º 7
0
def get_loan_detail_list(listing_ids):
    access_url = "http://gw.open.ppdai.com/invest/LLoanInfoService/BatchListingInfos"
    data = {"ListingIds": listing_ids}
    sort_data = rsa.sort(data)
    sign = rsa.sign(sort_data)
    list_result = client.send(access_url, json.dumps(data), appid, sign)

    # check result
    list_result_obj = json.loads(list_result.decode('utf-8'))
    if list_result_obj["Result"] == 1:
        return list_result_obj
    else:
        logging.error("Fail to get detail loan list.")
        return None
Ejemplo n.º 8
0
 def bid(self,ListingId):
     access_url = "https://openapi.ppdai.com/listing/openapi/bid"
     access_token = self.token
     data = {
     "ListingId": ListingId, 
     "Amount": 50,
     "UseCoupon":"true"
     }
     sort_data = rsa.sort(data)
     sign = rsa.sign(sort_data)
     list_result = client.send(access_url,json.dumps(data) , appid, sign,access_token)
     if list_result["Result"] != 0:
         log("bid faild",list_result)
     else:
         log("bid success",list_result)
Ejemplo n.º 9
0
 def send(url, data, appid, sign, accesstoken=''):
     utctime = datetime.datetime.utcnow()
     timestamp = utctime.strftime('%Y-%m-%d %H:%M:%S')
     headers = {
         "X-PPD-APPID": appid,
         "X-PPD-SIGN": sign,
         "X-PPD-TIMESTAMP": timestamp,
         "X-PPD-TIMESTAMP-SIGN": rsa.sign("%s%s" % (appid, timestamp))
     }
     if accesstoken.strip():
         headers["X-PPD-ACCESSTOKEN"] = accesstoken
     data = data.lower()
     result = http_client.http_post(url, data, headers=headers)
     print("send_data:%s" % (result))
     return result
Ejemplo n.º 10
0
 def send(url, data, appid, sign, accesstoken=''):
     utctime = datetime.datetime.utcnow()
     timestamp = utctime.strftime('%Y-%m-%d %H:%M:%S')
     headers = {
         "X-PPD-APPID": appid,
         "X-PPD-SIGN": sign,
         "X-PPD-TIMESTAMP": timestamp,
         "X-PPD-TIMESTAMP-SIGN": rsa.sign("%s%s" % (appid, timestamp)),
         "Accept": "application/json;charset=UTF-8"
     }
     if accesstoken.strip():
         headers["X-PPD-ACCESSTOKEN"] = accesstoken
     result = http_client.http_post(url, data, headers=headers)
     #print("send_data:\n%s" % (result))
     return json.loads(result)
Ejemplo n.º 11
0
def get_loan_list(index, date=None):  # date "2015-11-11 12:00:00.000"
    access_url = "http://gw.open.ppdai.com/invest/LLoanInfoService/LoanList"
    if date is None:
        data = {"PageIndex": index}
    else:
        data = {"PageIndex": index, "StartDateTime": date}
    sort_data = rsa.sort(data)
    sign = rsa.sign(sort_data)
    list_result = client.send(access_url, json.dumps(data), appid, sign)

    # check result
    list_result_obj = json.loads(list_result)
    if list_result_obj["Result"] == 1:
        return list_result_obj
    else:
        logging.error("Fail to get loan list.")
        return None
Ejemplo n.º 12
0
def getListingIdList():
    access_url = "https://openapi.ppdai.com/listing/openapiNoAuth/loanList"
    data = {
        "PageIndex": 1,
        "StartDateTime": "2015-11-11 12:00:00.000"
    }
    sort_data = rsa.sort(data)
    sign = rsa.sign(sort_data)
    list_result = client.send(access_url, json.dumps(data) , appid, sign)
    if (list_result["Result"] != 1):
        log("error getListingIdList")
        return []
    ListingIds = []
    for LoanInfo in list_result["LoanInfos"]:
        if LoanInfo["CreditCode"] != "AA":
            ListingIds.append(LoanInfo["ListingId"])
    return ListingIds
Ejemplo n.º 13
0
def make_bid(listing_id, amount):
    access_url = "http://gw.open.ppdai.com/invest/BidService/Bidding"
    access_token = "1ff70da4-909e-4ce0-ab17-0f75debd5c1d"
    data = {"ListingId": listing_id, "Amount": amount, "UseCoupon": "true"}
    sort_data = rsa.sort(data)
    sign = rsa.sign(sort_data)
    list_result = client.send(access_url, json.dumps(data), appid, sign,
                              access_token)

    # check result
    list_result_obj = json.loads(list_result)
    if list_result_obj["Result"] == 0:
        logging.info("Success to bid %s", listing_id)
        return list_result_obj
    else:
        logging.warning("Warning: fail to make bid %s. Reason: %s", listing_id,
                        list_result_obj["ResultMessage"])
        return None
Ejemplo n.º 14
0
                data = {
                    "StartTime":
                    time.strftime('%Y-%m-%d',
                                  time.localtime(float(StartTime))),
                    "EndTime":
                    time.strftime('%Y-%m-%d', time.localtime(float(current))),
                    "PageIndex":
                    1,
                    "PageSize":
                    500
                }

            while True:
                time.sleep(0.5)
                sort_data = rsa.sort(data)
                sign = rsa.sign(sort_data)
                list_result = client.send(access_url, json.dumps(data), APPID,
                                          sign, AccessToken)

                if list_result == '':
                    continue
                else:
                    list_result = json.loads(list_result)
                    break

            for item in list_result['BidList']:
                if int(item['ListingId']) == 0:
                    continue
                total += 1
                listings.append([
                    item['ListingId'],
Ejemplo n.º 15
0
def invest():
    if not 'OpenID' in session:
        return redirect(url_for('index'))

    refresh()
    # report()

    dataset = {}

    (db, cursor) = connectdb()
    cursor.execute("select * from json_data where page=%s", ['invest'])
    json_data = cursor.fetchall()
    dataset['json'] = {
        item['keyword']: json.loads(item['json'])
        for item in json_data
    }

    tmp = []
    for key, value in dataset['json']['strategy_stat'].items():
        value['name'] = key
        value[u'平均金额'] = int(value[u'总金额'] / value[u'数量'])
        for k, v in value.items():
            if k in ['平均利率', '平均期限']:
                value[k] = '%.2f' % value[k]
            elif k in ['10日坏标逾期率', '30日坏标逾期率', '90日坏标逾期率']:
                value[k] = '%.3f' % value[k]
        tmp.append(value)
    dataset['json']['strategy_stat'] = tmp

    cursor.execute("select * from strategy where OpenID=%s", ['0'])
    dataset['sys'] = cursor.fetchall()
    cursor.execute("select * from strategy where OpenID=%s",
                   [session['OpenID']])
    dataset['my'] = cursor.fetchall()
    cursor.execute("select strategy from user where OpenID=%s",
                   [session['OpenID']])
    if len(dataset['my']) < 4:
        dataset['add'] = True
    else:
        dataset['add'] = False

    dataset['strategy_count'] = 0

    dataset['strategy_weight'] = {u'初始评级': 0, u'借款利率': 0, u'借款期限': 0}
    sys_strategy = cursor.fetchone()['strategy']
    if not sys_strategy == '':
        sys_strategy = sys_strategy.split('-')
        for s in sys_strategy:
            for x in xrange(0, len(dataset['sys'])):
                if int(dataset['sys'][x]['id']) == int(s):
                    dataset['sys'][x]['active'] = 1
                    dataset['strategy_count'] += 1
                    content = json.loads(dataset['sys'][x]['content'])
                    for key in content.keys():
                        if dataset['strategy_weight'].has_key(key):
                            dataset['strategy_weight'][key] += 1
                    break

    for item in dataset['my']:
        if int(item['active']) == 1:
            content = json.loads(item['content'])
            for key in content.keys():
                if dataset['strategy_weight'].has_key(key):
                    dataset['strategy_weight'][key] += 1

    dataset['strategy_weight'] = {
        'x': [key for key in dataset['strategy_weight'].keys()],
        'data': [value for value in dataset['strategy_weight'].values()]
    }

    cursor.execute(
        "select balance, balanceBid, balanceWithdraw from user where OpenID=%s",
        [session['OpenID']])
    dataset['balance'] = cursor.fetchone()

    cursor.execute("select count(*) as count from bidding where OpenID=%s",
                   [session['OpenID']])
    dataset['bidding_count'] = cursor.fetchone()['count']

    cursor.execute(
        "select count(*) as count from strategy where OpenID=%s and active=%s",
        [session['OpenID'], 1])
    dataset['strategy_count'] += cursor.fetchone()['count']

    dates = []
    start = 1483200000
    while True:
        b = time2str(start, '%Y-%m-%d')
        if b[:4] == '2017':
            dates.append(b)
            start += 3600 * 24
        else:
            break
    dataset['calendar'] = {
        'count': {d: 0
                  for d in dates},
        'amount': {d: 0
                   for d in dates}
    }

    cursor.execute(
        "select * from bidding where OpenID=%s order by timestamp asc",
        [session['OpenID']])
    biddings = cursor.fetchall()
    for item in biddings:
        d = time2str(float(item['timestamp']), '%Y-%m-%d')
        dataset['calendar']['count'][d] += 1
        dataset['calendar']['amount'][d] += item['amount']

    dataset['calendar']['max_count'] = np.max(
        [v for v in dataset['calendar']['count'].values()])
    dataset['calendar']['count'] = [[
        d, dataset['calendar']['count'][d], dataset['calendar']['amount'][d]
    ] for d in dates]

    if len(biddings) > 0:
        cursor.execute(
            "select ListingId, CreditCode, Months, CurrentRate, Title from listing where ListingId in %s",
            [[x['ListingId'] for x in biddings]])
        tmp = cursor.fetchall()
        tmp = {str(t['ListingId']): t for t in tmp}
        d = []
        for x in range(0, len(biddings)):
            lid = str(biddings[x]['ListingId'])
            if tmp.has_key(lid):
                biddings[x]['CreditCode'] = tmp[lid]['CreditCode']
                biddings[x]['Months'] = tmp[lid]['Months']
                biddings[x]['CurrentRate'] = tmp[lid]['CurrentRate']
                biddings[x]['Title'] = tmp[lid]['Title']
                biddings[x]['timestamp'] = time2str(
                    float(biddings[x]['timestamp']), "%Y-%m-%d %H:%M:%S")
                d.append(biddings[x])
        biddings = d
        cursor.execute(
            "select id, name from strategy where OpenID=%s or OpenID=%s",
            ['0', session['OpenID']])
        tmp = cursor.fetchall()
        tmp = {str(t['id']): t['name'] for t in tmp}
        for x in range(0, len(biddings)):
            biddings[x]['strategy'] = tmp[str(biddings[x]['strategyId'])]
    dataset['biddings'] = biddings

    while True:
        access_url = "http://gw.open.ppdai.com/invest/LLoanInfoService/LoanList"
        data = {
            "PageIndex": 1,
        }
        sort_data = rsa.sort(data)
        sign = rsa.sign(sort_data)
        list_result = client.send(access_url, json.dumps(data), APPID, sign)
        if list_result == '':
            continue
        else:
            list_result = json.loads(list_result)
            break
    mapping = {}
    mapping['AAA'] = 15
    mapping['AA'] = 10
    mapping['A'] = 5
    mapping['B'] = 3
    mapping['C'] = 1
    mapping['D'] = 0
    mapping['E'] = 0
    mapping['F'] = 0
    colorset = {}
    colorset['AAA'] = 'rgba(243, 230, 162, 0.9)'
    colorset['AA'] = 'rgba(234, 126, 83, 0.9)'
    colorset['A'] = 'rgba(221, 107, 102, 0.9)'
    colorset['B'] = 'rgba(230, 157, 135, 0.9)'
    colorset['C'] = 'rgba(215, 135, 230, 0.9)'
    colorset['D'] = 'rgba(110, 113, 199, 0.9)'
    colorset['E'] = 'rgba(109, 188, 191, 0.9)'
    colorset['F'] = 'rgba(117, 179, 117, 0.9)'
    for x in range(0, len(list_result['LoanInfos'])):
        item = list_result['LoanInfos'][x]
        list_result['LoanInfos'][x]['score'] = mapping[item['CreditCode']] * (
            int(item['Rate']) - 9) * (6 / float(item['Months']))
        list_result['LoanInfos'][x][
            'ratio'] = 95 - 95 * item['RemainFunding'] / item['Amount']
        list_result['LoanInfos'][x]['color'] = colorset[item['CreditCode']]
    list_result['LoanInfos'].sort(key=lambda x: x['score'], reverse=True)
    dataset['listings'] = list_result['LoanInfos'][:10]
    if len(dataset['listings']) == 0:
        data['listing_max'] = 0.0000001
    else:
        dataset['listing_max'] = np.max(
            [float(x['score']) for x in dataset['listings']])
    for x in xrange(0, len(dataset['listings'])):
        dataset['listings'][x]['score'] = '%.2f' % (
            0.98 * dataset['listings'][x]['score'] / dataset['listing_max'])
        dataset['listings'][x]['Amount'] = int(
            dataset['listings'][x]['Amount'])
        dataset['listings'][x]['RemainFunding'] = int(
            dataset['listings'][x]['RemainFunding'])

    closedb(db, cursor)

    return render_template('invest.html',
                           auth=is_auth(),
                           datasetJson=json.dumps(dataset),
                           dataset=dataset)