Exemplo n.º 1
0
def eod_market_risk_detail_default_close_pd_run(valuation_date):
    r = utils.get_redis_conn(redis_ip)
    position_result = r.get(EOD_CUSTOM_POSITION_ + PE_DEFAULT_CLOSE.lower())
    position = JSONDecoder().decode(bytes.decode(position_result))

    if position:
        headers = utils.login(data_resource_ip, login_body)
        reports = eod_market_risk_detail_report_pd.eod_market_risk_detail_report(
            pd.DataFrame(position))

        instrument_contract_result = r.get(EOD_BASIC_INSTRUMENT_CONTRACT_TYPE)
        instruments_contract_dict = JSONDecoder().decode(
            bytes.decode(instrument_contract_result))
        for item in reports:
            item['exfsid'] = instruments_contract_dict.get(
                item.get('underlyerInstrumentId'))

        params = {
            'reportName': '全市场分品种风险报告_交易-收盘-自然日',
            'valuationDate': valuation_date,
            'reports': reports
        }
        utils.call_request(report_ip, 'report-service',
                           'rptMarketRiskDetailReportCreateBatch', params,
                           headers)
Exemplo n.º 2
0
def eod_position_run(pricing_environment):
    r = utils.get_redis_conn(ip)
    position_result = r.get(EOD_BASIC_POSITIONS)
    position = JSONDecoder().decode(bytes.decode(position_result))

    risk_result = r.get(EOD_BASIC_RISKS_ + pricing_environment.lower())
    risk = JSONDecoder().decode(bytes.decode(risk_result))

    cash_flow_result = r.get(EOD_BASIC_CASH_FLOW)
    cash_flow = JSONDecoder().decode(bytes.decode(cash_flow_result))

    headers = utils.login(ip, login_body)
    reports = eod_position_report(position, risk, cash_flow,
                                  pricing_environment, ip, headers)
    position_result = JSONEncoder().encode(reports)
    r.set(EOD_CUSTOM_POSITION_ + pricing_environment.lower(),
          str(position_result))

    now_date = datetime.now().date()
    pe_description = get_pricing_environment_description(
        pricing_environment, headers)
    params = {
        'reportName': POSITION_REPORT_ + pe_description,
        'valuationDate': str(now_date),
        'positionReports': reports
    }
    utils.call_request(ip, 'report-service', 'rptPositionReportCreateBatch',
                       params, headers)
Exemplo n.º 3
0
def eod_market_risk_by_book_underlyer_pd_run(pricing_environment,
                                             valuation_date):
    r = utils.get_redis_conn(redis_ip)
    position_result = r.get(EOD_CUSTOM_POSITION_ + pricing_environment.lower())
    position = JSONDecoder().decode(bytes.decode(position_result))

    if position:
        headers = utils.login(data_resource_ip, login_body)
        pe_description = utils.get_pricing_env_description(
            pricing_environment, data_resource_ip, headers)
        reports = eod_market_risk_by_book_underlyer_report_pd.eod_market_risk_by_book_underlyer_report(
            pd.DataFrame(position), pe_description)

        instrument_contract_result = r.get(EOD_BASIC_INSTRUMENT_CONTRACT_TYPE)
        instruments_contract_dict = JSONDecoder().decode(
            bytes.decode(instrument_contract_result))
        for item in reports:
            item['exfsid'] = instruments_contract_dict.get(
                item.get('underlyerInstrumentId'))

        params = {
            'reportName':
            MARKET_RISK_BY_BOOK_UNDERLYER_REPORT_ + pe_description,
            'valuationDate': valuation_date,
            'reports': reports
        }
        utils.call_request(report_ip, 'report-service',
                           'rptMarketRiskBySubUnderlyerReportCreateBatch',
                           params, headers)
Exemplo n.º 4
0
def eod_classic_scenarios_pd_run(valuation_date):
    r = utils.get_redis_conn(redis_ip)
    position_result = r.get(EOD_BASIC_POSITIONS)
    position = pd.read_msgpack(position_result)

    if not position.empty:
        sub_companies_result = r.get(EOD_BASIC_SUB_COMPANIES_FROM_ORACLE)
        all_sub_companies = JSONDecoder().decode(
            bytes.decode(sub_companies_result))

        headers = utils.login(data_resource_ip, login_body)
        pe_description = utils.get_pricing_env_description(
            PE_DEFAULT_CLOSE, data_resource_ip, headers)
        reports = eod_classic_scenarios_report_pd.eod_classic_scenarios_report(
            position, all_sub_companies, data_resource_ip, headers,
            valuation_date, PE_DEFAULT_CLOSE)

        instrument_contract_result = r.get(EOD_BASIC_INSTRUMENT_CONTRACT_TYPE)
        instruments_contract_dict = JSONDecoder().decode(
            bytes.decode(instrument_contract_result))
        for item in reports:
            item['exfsid'] = instruments_contract_dict.get(
                item.get('underlyerInstrumentId'))

        params = {
            'reportName':
            CLASSIC_SCENARIO_MARKET_RISK_REPORT_ + pe_description,
            'valuationDate': valuation_date,
            'reports': reports
        }
        utils.call_request(report_ip, 'report-service',
                           'rptMarketRiskDetailReportCreateBatch', params,
                           headers)
Exemplo n.º 5
0
def eod_hst_pnl_run(pricing_environment):
    r = utils.get_redis_conn(ip)
    position_result = r.get(EOD_CUSTOM_POSITION_ + pricing_environment.lower())
    position = JSONDecoder().decode(bytes.decode(position_result))

    cash_flow_result = r.get(EOD_BASIC_CASH_FLOW)
    cash_flow = JSONDecoder().decode(bytes.decode(cash_flow_result))

    underlyer_position_result = r.get(EOD_BASIC_UNDELRYER_POSITION_ +
                                      pricing_environment.lower())
    underlyer_position = JSONDecoder().decode(
        bytes.decode(underlyer_position_result))

    position_map_result = r.get(EOD_BASIC_POSITION_MAP)
    position_map = JSONDecoder().decode(bytes.decode(position_map_result))

    headers = utils.login(ip, login_body)
    pe_description = get_pricing_environment_description(
        pricing_environment, headers)
    reports = eod_historical_pnl_by_underlyer_report(position, cash_flow,
                                                     underlyer_position,
                                                     position_map,
                                                     pe_description)
    hst_pnl_result = JSONEncoder().encode(reports)
    r.set(EOD_CUSTOM_HST_PNL_ + pricing_environment.lower(),
          str(hst_pnl_result))
    now_date = datetime.now().date()
    params = {
        'reportName': HST_PNL_REPORT_ + pe_description,
        'valuationDate': str(now_date),
        'pnlHstReports': reports
    }
    utils.call_request(ip, 'report-service', 'rptPnlHstReportCreateBatch',
                       params, headers)
Exemplo n.º 6
0
def get_underlyer_positions(domain, headers, prcing_env):
    """Return exchange listed spot/future trade statistics."""
    books = utils.call_request(domain, 'trade-service',
                               'trdBookListBySimilarBookName',
                               {"similarBookName": ""}, headers)['result']
    listed_data = utils.call_request(domain, 'pricing-service',
                                     'prcPriceOnExchange', {
                                         "pricingEnvironmentId": prcing_env,
                                         'books': books
                                     }, headers)
    if 'result' in listed_data:
        underlyers = {}
        for l in listed_data['result']:
            if None in [
                    l[v] for v in [
                        'marketValue', 'price', 'delta', 'gamma', 'vega',
                        'theta', 'rhoR'
                    ]
            ]:
                continue
            temp_dict = underlyers.get(l['bookId'], {})
            temp_dict[l['instrumentId']] = l
            underlyers[l['bookId']] = temp_dict
        return underlyers
    else:
        raise RuntimeError('Failed to fetch spot/future trade statistics.')
Exemplo n.º 7
0
def eod_counter_party_market_risk_by_underlyer_default_close_pd_run(
        valuation_date):
    r = utils.get_redis_conn(redis_ip)
    position_result = r.get(EOD_CUSTOM_POSITION_ + PE_DEFAULT_CLOSE.lower())
    position = JSONDecoder().decode(bytes.decode(position_result))

    if position:
        sub_companies_result = r.get(EOD_BASIC_SUB_COMPANIES_FROM_ORACLE)
        all_sub_companies = JSONDecoder().decode(
            bytes.decode(sub_companies_result))

        headers = utils.login(data_resource_ip, login_body)
        reports = eod_market_risk_summary_report_pd.eod_counter_party_market_risk_by_underlyer_report(
            pd.DataFrame(position), all_sub_companies)

        instrument_contract_result = r.get(EOD_BASIC_INSTRUMENT_CONTRACT_TYPE)
        instruments_contract_dict = JSONDecoder().decode(
            bytes.decode(instrument_contract_result))
        for item in reports:
            item['exfsid'] = instruments_contract_dict.get(
                item.get('underlyerInstrumentId'))

        params = {
            'reportName': '交易对手分品种风险报告_交易-收盘-自然日',
            'valuationDate': valuation_date,
            'reports': reports
        }
        utils.call_request(
            report_ip, 'report-service',
            'rptCounterPartyMarketRiskByUnderlyerReportCreateBatch', params,
            headers)
def get_finanical_otc_client_fund(headers, ip):
    reports = []
    client_name_list = get_client_count_list(ip, headers)
    client_account_list = utils.call_request(
        ip, 'reference-data-service', 'clientAccountOpRecordList',
        {'accountIds': client_name_list[0]}, headers)['result']
    payment_list = utils.call_request(ip, 'reference-data-service',
                                      'cliFundEventSearch', {},
                                      headers)['result']
    for client in client_name_list[1]:
        report = {}
        report['clientName'] = client['legalName']  # 客户名称
        report['masterAgreementId'] = client['masterAgreementId']  # SAC主协议编码
        report['paymentIn'] = 0.0  # 入金
        report['paymentOut'] = 0.0  # 出金
        report['premiumBuy'] = 0.0  # 期权收取权利金(客户买期权)
        report['premiumSell'] = 0.0  # 期权支出权利金(客户卖期权)
        report['profitAmount'] = 0.0  # 期权了结盈利
        report['lossAmount'] = 0.0  # 期权了结亏损
        for client_account in client_account_list:
            if client_account['legalName'] == report['clientName']:
                if client_account[
                        'event'] == 'CHANGE_PREMIUM' or client_account[
                            'event'] == 'START_TRADE':
                    if client_account['cashChange'] > 0:
                        report['premiumSell'] += client_account[
                            'cashChange']  # 期权支出权利金(客户卖期权)
                    elif client_account['cashChange'] < 0:
                        report['premiumBuy'] += client_account[
                            'cashChange']  # 期权收取权利金(客户买期权)
                elif client_account[
                        'event'] == 'UNWIND_TRADE' or client_account[
                            'event'] == 'SETTLE_TRADE' or client_account[
                                'event'] == 'TERMINATE_TRADE':
                    if client_account['cashChange'] > 0:
                        report['profitAmount'] += client_account[
                            'cashChange']  # 期权了结盈利
                    elif client_account['cashChange'] < 0:
                        report['lossAmount'] += client_account[
                            'cashChange']  # 期权了结亏损

        for payment in payment_list:
            if payment['clientId'] == report['clientName']:
                if payment['paymentDirection'] == 'IN':
                    report['paymentIn'] += payment['paymentAmount']
                elif payment['paymentDirection'] == 'OUT':
                    report['paymentOut'] += payment['paymentAmount']

        report['paymentIn'] = abs(report['paymentIn'])
        report['paymentOut'] = abs(report['paymentOut'])
        report['premiumBuy'] = abs(report['premiumBuy'])
        report['premiumSell'] = abs(report['premiumSell'])
        report['profitAmount'] = abs(report['profitAmount'])
        report['lossAmount'] = abs(report['lossAmount'])
        report['fundTotal'] = report['paymentIn'] - report[
            'paymentOut'] - report['premiumBuy'] + report[
                'premiumSell'] - report['profitAmount'] + report['lossAmount']
        reports.append(report)
    return reports
Exemplo n.º 9
0
def process_listed_pos(positions, domain, headers, params):
    rpt = positions[[
        'bookId', 'delta', 'gamma', 'netPosition', 'expirationDate',
        'historySellAmount', 'historyBuyAmount', 'totalPnl', 'marketValue',
        'positionId', 'vega', 'vol', 'q', 'r', 'theta',
        'underlyerInstrumentId', 'underlyerInstrumentMultiplier', 'rhoR',
        'instrumentId', 'underlyerPrice', 'price'
    ]].fillna(0)
    rpt.rename(columns={
        'bookId': 'bookName',
        'netPosition': 'number',
        'totalPnl': 'pnl',
        'rhoR': 'rho',
        'underlyerInstrumentMultiplier': 'underlyerMultiplier'
    },
               inplace=True)
    # partyName,message and tradeDate has no value
    rpt['unwindNumber'] = 0
    rpt['unwindAmount'] = 0
    rpt['daysInYear'] = 365
    calc_delta_and_gamma(rpt)
    rpt['tradeId'] = rpt.apply(
        lambda row: row['bookName'] + '_' + row['instrumentId'], axis=1)
    rpt['initialNumber'] = rpt['number']
    rpt['premium'] = rpt['historySellAmount'] - rpt['historyBuyAmount']
    rpt['listedOption'] = True

    instrument_data = call_request(
        domain, 'market-data-service', 'mktInstrumentsListPaged',
        {'instrumentIds': list(rpt.instrumentId.dropna().unique())}, headers)
    instrument_df = pd.DataFrame(instrument_data['result']['page'])
    instrument_df['productType'] = instrument_df.apply(
        lambda row: 'VANILLA_EUROPEAN'
        if row.get('exerciseType') == 'EUROPEAN' else 'VANILLA_AMERICAN',
        axis=1)
    rpt = rpt.merge(instrument_df[['instrumentId', 'productType']],
                    on='instrumentId',
                    how='left')

    params['books'] = list(rpt.bookName.dropna().unique())
    listed_decay_data = call_request(domain, 'pricing-service',
                                     'prcPriceOnExchange', params, headers)
    listed_decay = pd.DataFrame(listed_decay_data['result'])
    listed_decay = listed_decay[listed_decay.positionId.isin(
        rpt.positionId)][['positionId', 'delta']]
    listed_decay.columns = ['positionId', 'deltaWithDecay']
    rpt = rpt.merge(listed_decay, on='positionId', how='left')
    rpt['deltaWithDecay'] = np.float64(rpt['deltaWithDecay']) / np.float64(
        rpt['underlyerMultiplier'])
    rpt['deltaDecay'] = rpt['deltaWithDecay'] - rpt['delta']
    rpt.drop(['historySellAmount', 'historyBuyAmount', 'instrumentId'],
             axis=1,
             inplace=True)
    rpt['positionId'] = rpt.apply(
        lambda row: row['positionId'][:-len('_portfolio_null')] if row[
            'positionId'].endswith('_portfolio_null') else row['positionId'],
        axis=1)
    return rpt
Exemplo n.º 10
0
def finanical_otc_client_fund_run():
    headers = utils.login(ip, login_body)
    now_date = datetime.now().date()
    reports = get_finanical_otc_client_fund(headers, ip)
    params = {
        "reportName": "finanical_otc_client_fund_report",
        "valuationDate": str(now_date),
        "finanicalOtcClientFundReports": reports
    }
    utils.call_request(ip, 'report-service',
                       'rptFinanicalOtcClientFundReportCreateBatch', params,
                       headers)
Exemplo n.º 11
0
def update_market_data(market_data_type):
    real_time_market_data_map = {}
    bad_instrument = set()
    instrument_map = {}
    instrument_id_map = {}
    header = utils.login('10.1.5.16', login_body)
    market_data_ip_list = get_ip_list()
    for this_ip in market_data_ip_list:
        instrument_map.clear()
        try:
            instrument_list = \
                utils.call_request(this_ip, 'market-data-service', 'mktInstrumentsListPaged', {}, header)['result'][
                    'page']
        except Exception as e:
            print("failed update market data for: " + this_ip + ",Exception:" +
                  str(e))
            continue
        quote_list = []
        for instrument in instrument_list:
            if not_valid_instrument(instrument):
                continue
            instrument_id = get_instrument_id(instrument).upper()
            instrument_id_map[instrument_id] = instrument['instrumentId']
            instrument_type = instrument_type_map[instrument['instrumentType']]
            quote_param = real_time_market_data_map.get(instrument_id, None)
            if quote_param is None:
                if instrument_id not in bad_instrument:
                    id_list = instrument_map.get(instrument_type, [])
                    id_list.append(instrument_id)
                    instrument_map[instrument_type] = id_list
                    bad_instrument.add(instrument_id)
            else:
                quote_list.append(quote_param)

        for (ins_type, ids) in instrument_map.items():
            if len(ids) == 0:
                continue
            market_datas = real_time_market_data_get(ins_type, ids)
            for market_data in market_datas:
                temp_id = market_data['instrumentId'].upper()
                instrument_id = instrument_id_map.get(temp_id, None)
                if instrument_id is None:
                    continue
                temp_quote_param = prepare_quote_param(market_data_type,
                                                       market_data,
                                                       instrument_id, ins_type)
                bad_instrument.discard(temp_id)
                real_time_market_data_map[temp_id] = temp_quote_param
                quote_list.append(temp_quote_param)
        utils.call_request(this_ip, 'market-data-service', 'mktQuoteSaveBatch',
                           {'quotes': quote_list}, header)
        print('done for ' + this_ip)
    print('all done')
Exemplo n.º 12
0
def basic_otc_company_type_run():
    sub_companies = basic_otc_company_type.get_sub_company_from_oracle()
    sub_companies_name = list(
        set(map(lambda i: i.get('clientName'), sub_companies)))
    r = utils.get_redis_conn(redis_ip)
    r.set(EOD_BASIC_SUB_COMPANIES_FROM_ORACLE,
          JSONEncoder().encode(sub_companies_name))
    print(' Basic SubCompanies Info from Oracle Has Save To Redis')
    headers = utils.login(data_resource_ip, login_body)
    params = {"infos": sub_companies}
    utils.call_request(report_ip, 'reference-data-service',
                       'refCompanyTypeInfoBatchCreate', params, headers)
Exemplo n.º 13
0
def eod_subject_computing_run(pricing_environment):
    headers = utils.login(ip, login_body)
    report = get_eod_subject_computing(ip, headers, pricing_environment)
    pe_description = get_pricing_environment_description(
        pricing_environment, headers)
    params = {
        "reportName": '资产统计表_' + pe_description,
        'reportType': RISK_REPORT_TYPE,
        "valuationDate": time.strftime("%Y-%m-%d", time.localtime()),
        "reports": [report]
    }
    utils.call_request(ip, 'report-service', 'rptCustomReportSaveBatch',
                       params, headers)
Exemplo n.º 14
0
def real_time_pnl_pd_run():
    r = utils.get_redis_conn(redis_ip)
    risk_result = r.get(INTRADAY_BASIC_RISKS)
    risk = pd.read_msgpack(risk_result)

    underlyer_position_result = r.get(INTRADAY_BASIC_UNDELRYER_POSITION)
    underlyer_position = pd.read_msgpack(underlyer_position_result)

    list_position_result = r.get(INTRADAY_BASIC_LISTED_OPTION_POSITION)
    list_position = pd.read_msgpack(list_position_result)

    cash_flow_today_result = r.get(INTRADAY_BASIC_CASH_FLOW_TODAY)
    cash_flow_today = pd.read_msgpack(cash_flow_today_result)

    live_position_index_result = r.get(INTRADAY_BASIC_POSITION_INDEX)
    live_position_index = pd.read_msgpack(live_position_index_result)

    today_terminated_position_index_result = r.get(
        INTRADAY_BASIC_TERMINATED_POSITION_INDEX)
    today_terminated_position_index = pd.read_msgpack(
        today_terminated_position_index_result)

    now_date = datetime.now().date()
    yst_date = now_date + timedelta(days=-1)
    yst_params = {
        'reportName': POSITION_REPORT,
        'valuationDate': str(yst_date)
    }
    headers = utils.login(ip, login_body)
    yst_position = utils.call_request(ip, 'report-service',
                                      'rptLatestPositionReportByNameAndDate',
                                      yst_params, headers)['result']
    yst_params['reportName'] = HST_PNL_REPORT
    yst_historical_pnl = utils.call_request(
        ip, 'report-service', 'rptLatestPnlHstReportByNameAndDate', yst_params,
        headers)['result']
    yst_position = pd.DataFrame(yst_position)
    yst_historical_pnl = pd.DataFrame(yst_historical_pnl)
    pe_description = utils.get_pricing_env_description(PE_DEFAULT_INTRADAY, ip,
                                                       headers)
    reports = intraday_daily_pnl_by_underlyer_report_pd.intraday_daily_pnl_by_underlyer_report(
        risk, cash_flow_today, underlyer_position, list_position,
        live_position_index, today_terminated_position_index, yst_position,
        yst_historical_pnl, pe_description)
    reports = utils.remove_nan_and_inf(reports.to_dict(orient='records'))
    pnl_result = JSONEncoder().encode(reports)
    r.set(PNL_QUEUE, str(pnl_result))
    r.publish(PNL_QUEUE, str(pnl_result))
Exemplo n.º 15
0
def get_underlyer_quotes(instrument_ids, valuation_time, domain, headers):
    """Return market value of underlying assets."""
    params = {
        'instrumentIds': instrument_ids,
        'valuationDate': valuation_time.strftime(_datetime_fmt),
        'timezone': None,
        'page': None,
        'pageSize': None
    }
    quote_data = utils.call_request(domain, 'market-data-service',
                                    'mktQuotesListPaged', params, headers)
    if 'result' in quote_data:
        quotes = quote_data['result']['page']
        id_to_quotes = {q['instrumentId']: q for q in quotes}
        if instrument_ids is not None and len(quotes) < len(instrument_ids):
            missing_ids = []
            for i in instrument_ids:
                if i not in id_to_quotes:
                    missing_ids.append(i)
                    id_to_quotes[i] = {
                        'instrumentId': i,
                        'last': None,
                        'bid': None,
                        'ask': None,
                        'close': None,
                        'settle': None,
                        'multiplier': None
                    }
            # raise RuntimeError('Missing quotes: {ids}'.format(ids=missing_ids))
        return id_to_quotes
    else:
        raise RuntimeError('Failed to fetch underlying asset quotes.')
Exemplo n.º 16
0
def get_portfolio_trades(domain, headers):
    portfolio_trades = {}
    portfolio_data = utils.call_request(domain, 'trade-service',
                                        'trdPortfolioTradesList', {}, headers)
    if 'result' in portfolio_data:
        portfolio_trades = portfolio_data['result']
    return portfolio_trades
Exemplo n.º 17
0
def get_all_account_data(headers):
    response_data = utils.call_request(ip, 'reference-data-service',
                                       'refBankAccountSearch', {}, headers)
    result = [(d['uuid'], d['bankAccount'], d['legalName'])
              for d in response_data['result']]
    print(result)
    return result
def save_client_valuation_report(domain, report, headers):
    params = {'valuationReports': [report]}
    result = utils.call_request(domain, 'report-service',
                                'rptValuationReportCreateOrUpdate', params,
                                headers)
    if 'error' in result:
        raise RuntimeError('Failed to save valuation report.')
Exemplo n.º 19
0
def eod_statics_of_risk_run(price_environment):
    headers = utils.login(ip, login_body)
    r = utils.get_redis_conn(ip)
    price_data = r.get(EOD_BASIC_RISKS_ + price_environment.lower())
    price_data = JSONDecoder().decode(bytes.decode(price_data))
    pe_description = get_pricing_environment_description(
        price_environment, headers)
    report = get_eod_statics_of_risk(price_data)
    params = {
        "reportName": '风险指标统计表_' + pe_description,
        'reportType': RISK_REPORT_TYPE,
        "valuationDate": time.strftime("%Y-%m-%d", time.localtime()),
        "reports": [report]
    }
    utils.call_request(ip, 'report-service', 'rptCustomReportSaveBatch',
                       params, headers)
def get_client_count_list(ip, headers):
    client_account_list = utils.call_request(ip, 'reference-data-service',
                                             'refPartyList', {},
                                             headers)['result']
    client_id = []
    for client in client_account_list:
        client_id.append(client['legalName'] + '0')
    return client_id, client_account_list
Exemplo n.º 21
0
def get_accounts(domain, headers):
    """Return client accounts."""
    accounts_data = utils.call_request(domain, 'reference-data-service',
                                       'clientAccountSearch', {}, headers)
    if 'result' in accounts_data:
        return accounts_data['result']
    else:
        raise RuntimeError('Failed to fetch client accounts.')
Exemplo n.º 22
0
def eod_market_risk_summary_run(pricing_environment):
    r = utils.get_redis_conn(ip)
    position_result = r.get(EOD_CUSTOM_POSITION_ + pricing_environment.lower())
    position = JSONDecoder().decode(bytes.decode(position_result))

    headers = utils.login(ip, login_body)
    reports = eod_market_risk_summary_report(position, pricing_environment)
    now_date = datetime.now().date()
    pe_description = get_pricing_environment_description(
        pricing_environment, headers)
    params = {
        'reportName': MARKET_RISK_REPORT_ + pe_description,
        'valuationDate': str(now_date),
        'reports': reports
    }
    utils.call_request(ip, 'report-service', 'rptMarketRiskReportCreateBatch',
                       params, headers)
Exemplo n.º 23
0
def get_funds(domain, headers):
    """Return account cash flows."""
    funds_data = utils.call_request(domain, 'reference-data-service',
                                    'cliFundEvnetListAll', {}, headers)
    if 'result' in funds_data:
        return funds_data['result']
    else:
        raise RuntimeError('Failed to fetch client account cash flows.')
Exemplo n.º 24
0
def get_risks(positions_list, pricing_environment, valuation_datetime, domain,
              headers):
    """Return pricing results of given positions.

    positions_list: list of basic positions(live, and possibly expiring positions)"""
    trade_ids = set()
    position_ids = set()
    for positions in positions_list:
        position_ids.update([p['positionId'] for p in positions.values()])
        trade_ids.update([p['tradeId'] for p in positions.values()])
    requests = ['price', 'delta', 'gamma', 'vega', 'theta', 'rho_r']
    params = {
        'requests': requests,
        'tradeIds': list(trade_ids),
        'pricingEnvironmentId': pricing_environment,
        'valuationDateTime': valuation_datetime.strftime(_datetime_fmt),
        'timezone': None
    }
    pricing_data = utils.call_request(domain, 'pricing-service', 'prcPrice',
                                      params, headers)
    if 'result' in pricing_data:
        risks = []
        for r in pricing_data['result']:
            if r['positionId'] not in position_ids:
                continue
            position_ids.remove(r['positionId'])
            risks.append(r)
            r['isSuccess'] = True
            r['message'] = ''
            for req in requests:
                if req == 'rho_r':
                    req = 'rhoR'
                if r[req] is None:
                    r['isSuccess'] = False
                    r['message'] = '定价返回空'
                    break
        for d in pricing_data['diagnostics']:
            p_id = d['key']
            if p_id in position_ids:
                position_ids.remove(p_id)
            risks.append({
                'positionId': p_id,
                'isSuccess': False,
                'message': d['message']
            })
        for p_id in position_ids:
            risks.append({
                'positionId': p_id,
                'isSuccess': False,
                'message': '定价返回空'
            })
        pe_description = utils.get_pricing_env_description(
            pricing_environment, domain, headers)
        for risk in risks:
            risk['pricing_environment'] = pe_description
        return {r['positionId']: r for r in risks}, pricing_data['result']
    else:
        raise RuntimeError('Failed to price trades.')
Exemplo n.º 25
0
def process_multi_asset_positions(positions, domain, headers, valuation_date):
    live_positions_df = positions[~positions['lcmEventType'].
                                  isin(CLOSED_POSITION_STATUS)]
    live_positions_df['asset.actualNotional'] = live_positions_df.apply(
        lambda row: actual_notional(row), axis=1)
    live_positions_df['actualPremium'] = live_positions_df.apply(
        lambda row: actual_premium(row), axis=1)
    live_positions_df['quantity1'] = np.float64(
        live_positions_df['asset.actualNotional']) / np.float64(
            live_positions_df['asset.initialSpot1'])
    live_positions_df['quantity2'] = np.float64(
        live_positions_df['asset.actualNotional']) / np.float64(
            live_positions_df['asset.initialSpot2'])

    trade_position_ids = list(
        map(lambda item: {
            'tradeId': item[1],
            'positionId': item[0]
        }, live_positions_df['tradeId'].iteritems()))
    # unwind number
    unwind_data = utils.call_request(domain, 'trade-service',
                                     'trdTradeLCMUnwindAmountGetAll',
                                     {'positionIds': trade_position_ids},
                                     headers)
    if 'result' in unwind_data:
        unwind_df = pd.DataFrame(unwind_data['result']).drop('tradeId', axis=1)
        live_pos_with_unwind = pd.merge(live_positions_df,
                                        unwind_df,
                                        on='positionId')
        live_pos_with_unwind['scalingFactor1'] = np.float64(
            live_pos_with_unwind['quantity1']) / np.float64(
                live_pos_with_unwind['asset.underlyerMultiplier1']
            ) / np.float64(live_pos_with_unwind['remainValue'])
        live_pos_with_unwind['initialNumber1'] = np.float64(
            live_pos_with_unwind['initialValue']) * np.float64(
                live_pos_with_unwind['scalingFactor1'])
        live_pos_with_unwind['unwindNumber1'] = np.float64(
            live_pos_with_unwind['historyValue']) * np.float64(
                live_pos_with_unwind['scalingFactor1'])

        live_pos_with_unwind['scalingFactor2'] = np.float64(
            live_pos_with_unwind['quantity2']) / np.float64(
                live_pos_with_unwind['asset.underlyerMultiplier2']
            ) / np.float64(live_pos_with_unwind['remainValue'])
        live_pos_with_unwind['initialNumber2'] = np.float64(
            live_pos_with_unwind['initialValue']) * np.float64(
                live_pos_with_unwind['scalingFactor2'])
        live_pos_with_unwind['unwindNumber2'] = np.float64(
            live_pos_with_unwind['historyValue']) * np.float64(
                live_pos_with_unwind['scalingFactor2'])

        expiring_cond = live_pos_with_unwind[
            'asset.expirationDate'] == valuation_date
        expiring_live_positions_df = live_pos_with_unwind[expiring_cond]
        non_expiring_live_positions_df = live_pos_with_unwind[~expiring_cond]
        return non_expiring_live_positions_df, expiring_live_positions_df
    else:
        raise RuntimeError('Failed to fetch trades.')
def get_mgn_margin_by_account_id(domain, accountId, headers):
    """Return client accounts."""
    params = {'accountIds': [accountId]}
    try:
        margin_data = utils.call_request(domain, 'reference-data-service',
                                         'mgnMarginList', params, headers)
        return margin_data['result'][0]
    except Exception as e:
        return None
Exemplo n.º 27
0
def get_cash_flows_today(domain, headers):
    """Return today's cash flow for each position."""
    cash_flow_data = utils.call_request(
        domain, 'trade-service', 'trdTradeLCMEventSearchByDate',
        {'date': datetime.now().strftime(_date_fmt)}, headers)
    if 'result' in cash_flow_data:
        return process_cash_flow(cash_flow_data['result'], True)
    else:
        raise RuntimeError("Failed to fetch today's cash flows.")
Exemplo n.º 28
0
def eod_market_risk_summary_pd_run(pricing_environment, valuation_date):
    r = utils.get_redis_conn(redis_ip)
    position_result = r.get(EOD_CUSTOM_POSITION_ + pricing_environment.lower())
    position = JSONDecoder().decode(bytes.decode(position_result))

    if position:
        headers = utils.login(data_resource_ip, login_body)
        reports = eod_market_risk_summary_report_pd.eod_market_risk_summary_report(
            pd.DataFrame(position), pricing_environment)
        pe_description = utils.get_pricing_env_description(
            pricing_environment, data_resource_ip, headers)
        params = {
            'reportName': MARKET_RISK_REPORT_ + pe_description,
            'valuationDate': valuation_date,
            'reports': reports
        }
        utils.call_request(report_ip, 'report-service',
                           'rptMarketRiskReportCreateBatch', params, headers)
Exemplo n.º 29
0
def eod_subsidiary_market_risk_default_close_pd_run(valuation_date):
    r = utils.get_redis_conn(redis_ip)
    position_result = r.get(EOD_CUSTOM_POSITION_ + PE_DEFAULT_CLOSE.lower())
    position = JSONDecoder().decode(bytes.decode(position_result))

    if position:
        headers = utils.login(data_resource_ip, login_body)
        reports = eod_market_risk_summary_report_pd.eod_subsidiary_market_risk_report(
            pd.DataFrame(position))

        params = {
            'reportName': '各子公司整体风险报告_交易-收盘-自然日',
            'valuationDate': valuation_date,
            'reports': reports
        }
        utils.call_request(report_ip, 'report-service',
                           'rptSubsidiaryMarketRiskReportCreateBatch', params,
                           headers)
Exemplo n.º 30
0
def get_portfolio_trades(domain, headers):
    result = []
    portfolio_data = utils.call_request(domain, 'trade-service', 'trdPortfolioTradesList', {}, headers)
    if 'result' in portfolio_data:
        portfolio_trades = portfolio_data['result']
        for portfolio_name in portfolio_trades:
            trade_ids = portfolio_trades[portfolio_name]
            for trade_id in trade_ids:
                result.append({'tradeId': trade_id, 'portfolioName': portfolio_name})
    return pd.DataFrame(result)