Exemplo n.º 1
0
def save_old_sales_data():
    r = utils.get_redis_conn(domain)
    sales_result = r.get('data:sales')
    sales = JSONDecoder().decode(bytes.decode(sales_result))
    sub_branch_result = r.get('data:sub_branch')
    sub_branch = JSONDecoder().decode(bytes.decode(sub_branch_result))

    headers = utils.login(domain, login_body)
    sub_map = {}
    branch_map = {}
    for branch in sub_branch:
        sub_name = branch['subsidiary']
        if sub_name not in sub_map:
            sub_result = utils.call_request(domain, 'reference-data-service',
                                            'refSubsidiaryCreate',
                                            {'subsidiaryName': sub_name},
                                            headers)['result']
            sub_map[sub_name] = sub_result['subsidiaryId']
        branch_name = branch['branch']
        branch_result = utils.call_request(
            domain, 'reference-data-service', 'refBranchCreate', {
                'subsidiaryId': sub_map[sub_name],
                'branchName': branch_name
            }, headers)['result']
        branch_map[branch_name] = branch_result['branchId']
    for sale in sales:
        sale_name = sale['salesName']
        branch_id = branch_map[sale['branch']]
        utils.call_request(domain, 'reference-data-service', 'refSalesCreate',
                           {
                               'branchId': branch_id,
                               'salesName': sale_name
                           }, headers)
Exemplo n.º 2
0
def import_sheet_0(ip, headers):
    # 获取所有交易对手列表
    party_names = \
        utils.call_request(ip, 'reference-data-service', 'refSimilarLegalNameList', {'similarLegalName': ''}, headers)
    print('BCT交易对手名称列表: {party_names}'.format(party_names=party_names))
    # 获取所有标的物列表
    instrument_ids = utils.call_request(ip, 'market-data-service',
                                        'mktInstrumentIdsList', {}, headers)
    print('BCT标的物列表: {instrument_ids}'.format(instrument_ids=instrument_ids))

    df = pd.read_excel(trade_excel_file, header=1)
    for i, v in df.iterrows():
        if i == 0:
            continue
        underlyer = instrument_wind_code(v['undercode'], instrument_ids)
        if v['undercode'].find('.') < 0 and underlyer == v['undercode']:
            print('BCT不存在合约代码 {underlyer} '.format(underlyer=str(underlyer)))
            continue
        trade_id = v['internalID']
        book = book_name
        trade_date = datetime.strptime(str(v['T0']), _date_fmt)
        option_type = _OPTION_CALL if v['opt_base_type'].upper(
        ) == 'Call' else _OPTION_PUT
        strike_type = _UNIT_CNY
        strike = v['strike']
        direction = _DIRECTION_SELLER if v['side'] == '卖方' else _DIRECTION_BUYER
        multiplier = 1
        specified_price = 'close'
        init_spot = v['S0']
        expiration_date = datetime.strptime(str(v['T']), _date_fmt)
        notional_amount_type = _UNIT_CNY
        notional = v['notional']
        participation_rate = v['participation']
        annualized = False
        term = (datetime.strptime(str(v['T']), _date_fmt) -
                datetime.strptime(str(v['T0']), _date_fmt)).days
        days_in_year = _DAYS_IN_YEAR
        premium_type = _UNIT_CNY
        premium = v['totalPx']
        effective_date = datetime.strptime(str(v['T0']), _date_fmt)
        trader = ''
        counter_party = v['counterparty']
        sales = ''
        trade = trade_templates.vanilla_european(
            trade_id, book, trade_date, option_type, strike_type, strike,
            direction, underlyer, multiplier, specified_price, init_spot,
            expiration_date, notional_amount_type, notional,
            participation_rate, annualized, term, days_in_year, premium_type,
            premium, effective_date, trader, counter_party, sales)
        print('BCT交易信息: {trade} '.format(trade=str(trade)))
        try:
            create_trade_and_client_cash_flow(trade, login_ip, headers)
        except Exception as e:
            logging.info('导入交易信息出错: {error} '.format(error=str(e)))
Exemplo n.º 3
0
def get_old_sales_data():
    headers = utils.login(domain, login_body)
    sales = utils.call_request(domain, 'reference-data-service',
                               'refSalesList', {}, headers)['result']
    sub_branch = utils.call_request(domain, 'reference-data-service',
                                    'refSubsidiaryBranchList', {},
                                    headers)['result']
    print(sub_branch)
    print(sales)

    r = utils.get_redis_conn(domain)
    sales_result = JSONEncoder().encode(sales)
    sub_branch_result = JSONEncoder().encode(sub_branch)
    r.set('data:sales', str(sales_result))
    r.set('data:sub_branch', str(sub_branch_result))
Exemplo n.º 4
0
def check_and_save_market_data(data, instrument_id):
    if not data:
        quote = market_data_dict.get(instrument_id)
        if quote:
            utils.call_request(ip, "market-data-service", "mktQuoteSave",
                               build_params(quote['close'], instrument_id),
                               headers)
    else:
        result = data[0]
        quote = result['quote']
        if not quote.get('close'):
            quote = market_data_dict.get(instrument_id)
            if quote:
                utils.call_request(ip, "market-data-service", "mktQuoteSave",
                                   build_params(quote['close'], instrument_id),
                                   headers)
Exemplo n.º 5
0
def create_eod_daily_pnl(pricing_environment):
    params = {
        'reportName': PNL_REPORT_ + pricing_environment.lower(),
        'valuationDate': now_date,
        'pnlReports': [{}]
    }
    return utils.call_request('rptPnlReportCreateBatch', params,
                              'report-service', host, token)
Exemplo n.º 6
0
def create_finanical_otc_client_fund():
    params = {
        "reportName": "finanical_otc_client_fund_report",
        "valuationDate": now_date,
        "finanicalOtcClientFundReports": [{}]
    }
    return utils.call_request('rptFinanicalOtcClientFundReportCreateBatch',
                              params, 'report-service', host, token)
Exemplo n.º 7
0
def create_financial_otc_fund_detail():
    params = {
        'reportName': 'financial_otc_fund_detail_report',
        'valuationDate': now_date,
        'financialOtcFundDetailReports': [{}]
    }
    return utils.call_request('rptFinancialOtcFundDetailReportCreateBatch',
                              params, 'report-service', host, token)
Exemplo n.º 8
0
def create_financial_otc_trade():
    params = {
        'reportName': 'financial_otc_trade_report_default_close',
        'valuationDate': now_date,
        'otcTradeReports': [{}]
    }
    return utils.call_request('rptOtcTradeReportCreateBatch', params,
                              'report-service', host, token)
Exemplo n.º 9
0
def get_last_market_data(ip, headers):
    params = {
        'instrumentIds': [],
        'valuationDate': None,
        'timezone': 'Asia/Shanghai',
        'page': None,
        'pageSize': None
    }
    quote_page_list = utils.call_request(ip, 'market-data-service',
                                         'mktQuotesListPaged', params,
                                         headers)['result']['page']
    market_dict = {}
    if not quote_page_list:
        return None
    else:
        for quote in quote_page_list:
            market_dict[quote['instrumentId']] = quote
        return market_dict
Exemplo n.º 10
0
def import_wind_close_market_data(ip, headers, date_str):
    print('close_thread')
    w.start()
    start = datetime.strptime(date_str, '%Y-%m-%d').date()
    end = start
    instrument_list_response = utils.call_request(ip, "market-data-service",
                                                  "mktInstrumentsListPaged",
                                                  {}, headers)
    tickers = []
    if "error" not in instrument_list_response:
        for i in instrument_list_response['result']['page']:
            tickers.append(i['instrumentId'])
    for ticker in tickers:
        # ticker="abcdefg"
        data = get(ticker, start, end)
        check_and_save_market_data(data, ticker)
        for q in data:
            save(q)
    w.close()
Exemplo n.º 11
0
def save(quote):
    params = quote
    try:
        ts = time_time.time()
        json = utils.call_request(ip, "market-data-service", "mktQuoteSave",
                                  params, headers)
        te = time_time.time()
        t = str(te - ts)
        logging.info("saving instrument " + quote['instrumentId'] +
                     " into BCT in " + t)
        if 'error' in json:
            logging.info("failed to save quote " + quote['instrumentId'] +
                         " " + quote['valuationDate'] +
                         json['error']['message'])
        else:
            logging.info("success: saved quote " + quote['instrumentId'] +
                         " " + quote['valuationDate'])
    except Exception as e:
        logging.info("failed to save quote " + quote['instrumentId'] +
                     ". network error?")
Exemplo n.º 12
0
def trade_upgrade():
    headers = utils.login(domain, login_body)
    utils.call_request(domain, 'trade-service', 'trdTradeGenerateHistoryIndex',
                       {}, headers)
    utils.call_request(domain, 'trade-service', 'tradeRepairHistoryCashFlow',
                       {}, headers)
Exemplo n.º 13
0
def import_sheet_0(ip, headers):
    workbook = openpyxl.load_workbook(party_excel_file)
    sheet0 = workbook['有交易']
    count = 0
    natures_normal = ['国企', '私企', '普通产业客户']
    natures_fin = ['保险公司', '券商', '同业', '私募', '资管', '银行']
    categories_normal = ['普通投资者']
    categories_pro = ['专业投资者']
    for r in sheet0.rows:
        count += 1
        if count < 4:
            continue
        row = [item.value for item in r]
        party = {
            'legalName': row[4],
            'legalRepresentative': '-',
            'address': '-',
            'contact': '-',
            'warrantor': '-',
            'warrantorAddress': '-',
            'tradePhone': '-',
            'tradeEmail': '-',
            'subsidiaryName': '-',
            'branchName': '-',
            'salesName': '-',
            'masterAgreementId': 'ROW_' + ('%05d' % count)
        }

        print('-----第 {i} 行-----'.format(i=count))
        if row[13] is None or (row[13] not in ['0', '1', 0, 1]):
            print('是否产品不正确', row[0], row[4], row[13])
            party['clientType'] = 'PRODUCT' if row[4].endswith(
                '基金') else 'INSTITUTION'
        else:
            party['clientType'] = 'PRODUCT' if row[13] in ['1', 1
                                                           ] else 'INSTITUTION'

        has_category = True
        if row[14] is None or (row[14] not in categories_normal
                               and row[14] not in categories_pro):
            has_category = False
            print('投资者类别不正确', row[0], row[4], row[14])

        has_nature = True
        if row[16] is None or (row[16] not in natures_normal
                               and row[16] not in natures_fin):
            has_nature = False
            print('投资者性质不正确', row[0], row[4], row[16])

        if has_category and has_nature:
            if party['clientType'] == 'PRODUCT':
                party['investorType'] = 'FINANCIAL_PRODUCT'
            elif row[14] in categories_pro and row[16] in natures_fin:
                party['investorType'] = 'FINANCIAL_INSTITUTIONAL_INVESTOR'
            elif row[14] in categories_pro and row[16] not in natures_fin:
                party['investorType'] = 'PROFESSIONAL_INVESTOR'
            elif row[14] not in categories_pro and row[16] not in natures_fin:
                party['investorType'] = 'NON_PROFESSINAL_INVESTOR'
            elif party['legalName'].startswith('新湖-') \
                    or party['legalName'].find('保险') > 0 \
                    or party['legalName'].find('证券') > 0 \
                    or party['legalName'].find('银行') > 0 \
                    or party['legalName'].find('资产管理') > 0 \
                    or party['legalName'].find('风险管理') > 0 \
                    or party['legalName'].find('投资管理') > 0:
                party['investorType'] = 'FINANCIAL_INSTITUTIONAL_INVESTOR'
            else:
                print('* 请确定是否为一般机构投资者:', party['legalName'])
                party['investorType'] = 'NON_PROFESSINAL_INVESTOR'

        if row[17] is None or (re.search(r'C[1-5]?', row[17]) is None):
            print('评级不正确', row[0], row[4], row[17])
            party['clientLevel'] = 'LEVEL_C'
        else:
            party['clientLevel'] = 'LEVEL_C'

        print(party)
        utils.call_request(ip, 'reference-data-service', 'refPartySave', party,
                           headers)
    print(count)