Пример #1
0
def groupToTicket(group):
    """
	[List] group of tickets => [Dictionary] ticket
	"""
    isActiveTicket = lambda g: \
     g[0]['Repo Sta'] == 'Active'


    getMrcTicket = lambda g: \
     firstOf(lambda el: el['Type'] == 'MRC', g)

    getRtTicket = lambda g: \
     firstOf(lambda el: el['Type'] == 'RT', g)

    getKmrTicket = lambda g: \
     firstOf(lambda el: el['Type'] == 'KMR', g)

    getCrTicket = lambda g: \
     firstOf(lambda el: el['Type'] == 'CR', g)


    return \
    mergeDictionary(getRtTicket(group), {'Tkt #': getMrcTicket(group)['Tkt #']}) \
    if isActiveTicket(group) else \
    mergeDictionary(getCrTicket(group), {'Orig Tkt': getKmrTicket(group)['Orig Tkt']})
Пример #2
0
def getCashFromBalancenActivityFiles(balanceFile, activityFile):
    """
	[String] balanceFile, [String] activityFile
		=> ( [String] date
		   , [Iterable] cash entries
		   )
	"""
    checkFileDates = compose(
     lambda t: lognRaise('checkFileDates(): inconsistant dates from filenames') \
         if t[0] != t[1] else t[0]
      , lambda file1, file2: ( getDateFromFileName(file1)
             , getDateFromFileName(file2)
             )
    )


    processFiles = lambda date, balFile, actFile: compose(
     partial(map, partial(mergeDictionary, {'date': date, 'custodian':''}))
      , lambda d: d.values()
      , lambda _1, balFile, actFile: \
        mergeDictionary( getCashFromBalance(fileToLines(balFile))
               , getCashFromActivity(fileToLines(actFile))
               )
    )(date, balFile, actFile)

    return compose(
        lambda date: (date, processFiles(date, balanceFile, activityFile)),
        lambda _: checkFileDates(balanceFile, activityFile),
        lambda _1, _2: lognContinue(
            'getCashFromBalancenActivityFiles(): {0}, {1}'.format(
                balanceFile, activityFile), 0))(balanceFile, activityFile)
Пример #3
0
def writeAccumulateTradeFile(outputDir, portfolio, date, positions):
    """
	[String] outputDir (the directory to write the csv file)
	[String] portfolio
	[String] date (yyyy-mm-dd)
	[Iterator] positions (the positions from the trade file) 
		=> [String] csv file

	From the date and positions of the Bloomberg AIM trade file, write the
	accumulated trade file.

	Here we assume that accumulated trade files of previous days are also located
	on the outputDir.
	"""
    prefix = 'Equities_' if portfolio == '11490' \
       else 'Equities_BOC_' if portfolio == '11500' \
       else 'Equities_A-MC-P_' # 13006

    outputFile = join(
        outputDir, prefix +
        datetime.strftime(datetime.strptime(date, '%Y-%m-%d'), '%d%m%Y') +
        '.csv')

    shutil.copyfile(getNearestAccumulateFile(outputDir, portfolio, date),
                    outputFile)


    toNewPostion = lambda position: mergeDictionary(
     position
      , { 'FundName': 'CLT-CLI HK BR (CLASS A-HK) Trust Fund' if position['Fund'].startswith('11490') \
           else 'CLT-CLI HK BR (CLASS A-HK) Trust Fund_BOC' if position['Fund'].startswith('11500') \
           else 'CLT-CLI Macau BR (Class A-MC) Trust Fund-Par' if position['Fund'].startswith('13006') \
           else lognRaise('toNewPostion(): invalid fund name {0}'.format(position['Fund']))
     , '': ''
     , 'BuySell': 'Buy' if position['B/S'] == 'B' else 'Sell'
     }
    )

    headers = [
        'FundName', '', 'Ticker & Exc', 'Shrt Name', 'Amount Pennies',
        'BuySell', 'FACC Long Name', 'As of Dt', 'Stl Date', 'Price'
    ]

    positionToValues = lambda position: map(lambda key: position[key], headers)

    # [Iterator] positions => [String] output string to be written to the file
    toOutputString = compose(
        lambda rows: '\n'.join(rows) + '\n',
        partial(map, lambda values: ','.join(values)),
        partial(map, lambda values: map(str, values)),
        partial(map, positionToValues), partial(map, toNewPostion),
        partial(filter, lambda p: p['Fund'].startswith(portfolio)))

    with open(outputFile, 'a') as newFile:
        newFile.write(toOutputString(positions))
        return 0
Пример #4
0
def writeTrusteeTradeFile(outputDir, portfolio, date, positions):
    """
	[String] outputDir (the directory to write the csv file)
	[String] portfolio
	[String] date (yyyy-mm-dd)
	[Iterator] positions (the positions from the trade file) 
		=> [String] csv file

	From the date and positions of the Bloomberg AIM trade file, write the CL 
	trustee trade file.
	"""
    updatePosition = lambda p: \
     mergeDictionary(p, {'Broker Long Name': p['FACC Long Name']})

    headers = [
        'Fund', 'Ticker & Exc', 'ISIN', 'Shrt Name', 'B/S', 'Yield',
        'As of Dt', 'Stl Date', 'Amount Pennies', 'Price', 'Bkr Comm',
        'Stamp Duty', 'Exch Fee', 'Trans. Levy', 'Misc Fee', 'Crcy',
        'Broker Long Name', 'Accr Int', 'Settle Amount', 'L1 Tag Nm'
    ]

    positionToValues = lambda position: map(lambda key: position[key], headers)

    def getOutputFileName(portfolio, date, outputDir):
        prefix = 'Order Record of A-HK Equity ' if portfolio == '11490' \
           else 'Order Record of A-HK Equity_BOC ' if portfolio == '11500' \
           else 'Order Record of A-MC-P Equity' # 13006

        return join(
            outputDir, prefix +
            datetime.strftime(datetime.strptime(date, '%Y-%m-%d'), '%y%m%d') +
            '.csv')


    getOutputRows = lambda portfolio, date, positions: \
     chain( [ ['China Life Franklin - CLT-CLI HK BR (CLASS A-HK) TRUST FUND' \
        if portfolio == '11490' else \
        'China Life Franklin - CLT-CLI HK BR (CLASS A-HK) TRUST FUND_BOC' \
        if portfolio == '11500' else \
        'CLT-CLI Macau BR (Class A-MC) Trust Fund-Par' #13006
        ]
         , ['{0} Equity FOR {0} ON '.format(portfolio) \
           + datetime.strftime(datetime.strptime(date, '%Y-%m-%d'), '%m/%d/%y')
           ]
         , [''] # an empty row
         , headers
         ]
       , map( positionToValues
          , map( updatePosition
              , filter(lambda p: p['Fund'].startswith(portfolio), positions)))
       )

    return writeCsv(getOutputFileName(portfolio, date, outputDir),
                    getOutputRows(portfolio, date, positions),
                    delimiter=',')
Пример #5
0
def ticketToTrade(ticket):
    """
	[Dictionary] REPO trade ticket (Bloomberg)
		=> [Dictionary] BOCI Prudential trade
	"""
    t = {}
    t['Portfolio_code'] = getAccountNumber(ticket['Fund'])
    t['Txn_type'] = 'REPO'
    t['Txn_sub_type'] = 'Close' if ticket['Repo Sta'] == 'Closed' else \
         'Change Rate' if ticket['Trd Dt'] > ticket['Stl Date'] else \
         'Open'
    t['Trade_date'] = toDateTimeString(ticket['Trd Dt']) if t['Txn_sub_type'] == 'Open' \
         else ''
    t['Settle_date'] = toDateTimeString(ticket['Stl Date']) if t['Txn_sub_type'] == 'Open' \
         else ''
    t['Mature_date'] = '' if t['Txn_sub_type'] == 'Change Rate' else \
         toDateTimeString(ticket['Trd Dt']) if t['Txn_sub_type'] == 'Close' else \
         '31/12/2049' if ticket['Trm Date'] == 'OPEN' else \
         toDateTimeString(ticket['Trm Date'])
    t['Loan_ccy'] = '' if t['Txn_sub_type'] == 'Change Rate' else ticket['Crcy']
    t['Amount'] = '' if t['Txn_sub_type'] == 'Change Rate' else ticket[
        'Loan Amount']
    t['Eff_date'] = '' if t['Txn_sub_type'] == 'Close' else \
        toDateTimeString(ticket['Stl Date']) if t['Txn_sub_type'] == 'Open' \
        else toDateTimeString(ticket['Trd Dt'])
    t['Int_rate'] = '' if t['Txn_sub_type'] == 'Close' else ticket['Repo Rte']
    t['Int_mode'] = '' if t['Txn_sub_type'] == 'Close' else 'ACT/360'
    t['Col_ISIN'] = '' if t['Txn_sub_type'] == 'Change Rate' else ticket['ISIN']
    t['Col_Qty'] = '' if t['Txn_sub_type'] == 'Change Rate' else \
        1000 * toNumber(ticket['Amount'])
    t['Broker'] = '' if t['Txn_sub_type'] == 'Change Rate' else ticket[
        'Broker ID']
    t['Cust_ref'] = toStringIfFloat(ticket['Orig Tkt']) if t['Txn_sub_type'] == 'Close' \
        else toStringIfFloat(ticket['Tkt #'])

    return mergeDictionary(
        t, {
            'Col_SEDOL': '',
            'Col_Bloomberg': '',
            'Col_LocalCode': '',
            'Col_CMUCode': '',
            'Col_desc': '',
            'Exchange': ''
        })
Пример #6
0
 def combinePositions(acc, el):
     return acc if el['currency'] in acc else \
     mergeDictionary( acc
           , {el['currency']: valmap(lambda v: removeBOM(v) if isinstance(v, str) else v, el)}
           )
Пример #7
0
	Change two date fields (As of Dt, Stl Date) into a string format (yyyy-mm-dd)
"""
updatePosition = lambda p: \
 mergeDictionary( p
       , { 'Fund': toStringIfFloat(p['Trader Name'])
         , 'Ticker & Exc': p['Ticker and Exchange Code']
         , 'ISIN': p['ISIN Number']
         , 'Shrt Name': p['Short Name']
         , 'Crcy': p['Currency']
         , 'B/S': p['Buy/Sell']
         , 'Amount Pennies': p['Amount (Pennies)']
         , 'Price': p['Trade price']
         , 'Settle Amount': p['Settlement Total in Settlemen']
         , 'Bkr Comm': p['Transaction Cost 1 Amount']
         , 'Stamp Duty': p['Transaction Cost 2 Amount']
         , 'Exch Fee': p['Transaction Cost 3 Amount']
         , 'Trans. Levy': p['Transaction Cost 4 Amount']
         , 'Misc Fee': p['Transaction Cost 5 Amount']
         , 'As of Dt': datetime.strftime( fromExcelOrdinal(p['As of Date'])
              , '%Y-%m-%d')
         , 'Stl Date': datetime.strftime( fromExcelOrdinal(p['Settlement Date'])
              , '%Y-%m-%d')
         , 'Accr Int': p['Accrued Interest']
         , 'FACC Long Name': p['Firm Account Long Name']
         , 'L1 Tag Nm': 'Trading' if p['Level 1 Tag Name'] == 'AFS' and p['Trader Name'] == '11490-B' \
             else p['Level 1 Tag Name']
         }
       )


def lognContinue(msg, x):