Example usage for org.apache.commons.collections15.keyvalue MultiKey MultiKey

List of usage examples for org.apache.commons.collections15.keyvalue MultiKey MultiKey

Introduction

In this page you can find the example usage for org.apache.commons.collections15.keyvalue MultiKey MultiKey.

Prototype

public MultiKey(K[] keys, boolean makeClone) 

Source Link

Document

Constructor taking an array of keys, optionally choosing whether to clone.

Usage

From source file:com.jgoetsch.ib.handlers.SingleHandlerManager.java

public synchronized void addHandler(String eventName, int objectId, EWrapper handler) {
    if (handler == null)
        handlerMap.remove(eventName, objectId);
    else {//  w  w  w. j a va2  s  .  c  om
        handlerMap.put(eventName, objectId, handler);
        handlerReverseMap.put(handler, new MultiKey<Object>(eventName, objectId));
    }
}

From source file:eu.crisis_economics.abm.markets.clearing.IncrementalLoanDistributionAlgorithm.java

private Pair<Double, Double> distributeLoans(final Map<String, Borrower> borrowers,
        final Map<String, Lender> lenders, final Map<String, Double> loanDemands,
        final Map<String, Double> loanSupplies, final Map<Pair<String, String>, Double> interestRates) {

    // collect amount demanded by each firm at the current interest rate
    Map<String, Double> updatedLoanDemand = new HashMap<String, Double>();
    for (String key : loanDemands.keySet())
        updatedLoanDemand.put(key, 0.);/*from   ww w.ja  v a 2 s .c om*/

    Map<String, Double> updatedLoanSupply = new HashMap<String, Double>();
    Map<String, Double> loanSuppliesCopy = new HashMap<String, Double>();
    for (String key : loanSupplies.keySet()) {
        updatedLoanSupply.put(key, 0.);
        loanSuppliesCopy.put(key, loanSupplies.get(key));
    }

    /** 
      * Aggregation for loans. Loans between the same participant pair (the
      * same lender-borrower pair) will be combined, by extension of the loan
      * principal, until the cash aggreation threshold LOAN_AGGREGATION_THRESHOLD
      * is reached. At this point, a new loan contract will instead be created.
      */
    class LoanAggregator {
        private static final double LOAN_AGGREGATION_THRESHOLD = 5.e7;
        private Map<MultiKey<String>, Stack<Loan>> newLoanContracts = new HashMap<MultiKey<String>, Stack<Loan>>();

        // Establish a new effective loan, either (a) by creating a loan contract, or
        // (b) by extending the principal sum of an existing loan.
        void establishNew(String borrowerID, String lenderID, double principalValue) {
            MultiKey<String> contractKey = new MultiKey<String>(borrowerID, lenderID);
            Stack<Loan> existingLoans = newLoanContracts.get(contractKey);
            if (existingLoans == null) {
                existingLoans = new Stack<Loan>();
                newLoanContracts.put(contractKey, existingLoans);
                existingLoans.push(createNewLoan(borrowerID, lenderID, principalValue));
            } else if (existingLoans.peek().getLoanPrincipalValue() < LOAN_AGGREGATION_THRESHOLD) {
                extendExistingLoan(existingLoans.peek(), principalValue);
            } else
                existingLoans.push(createNewLoan(borrowerID, lenderID, principalValue));
        }

        // Create a new loan contract.
        private Loan createNewLoan(String borrowerID, String lenderID, double principalValue) {
            return setupLoanContract(borrowers.get(borrowerID), lenders.get(lenderID), principalValue,
                    interestRates.get(new Pair<String, String>(borrowerID, lenderID)));
        }
    }
    LoanAggregator loanAggregator = new LoanAggregator();

    final Iterator<Entry<String, Double>> firmIter = loanDemands.entrySet().iterator();
    while (firmIter.hasNext()) {
        Entry<String, Double> firm = firmIter.next();
        final Iterator<Entry<String, Double>> bankIter = loanSuppliesCopy.entrySet().iterator();
        while (bankIter.hasNext()) {
            Entry<String, Double> bank = bankIter.next();
            // leverage circle in case lender == borrower's depositor - try same bank again
            while (updatedLoanDemand.get(firm.getKey()) < firm.getValue()
                    && updatedLoanSupply.get(bank.getKey()) < bank.getValue()) {
                double reserves = ((Bank) lenders.get(bank.getKey())).getCashReserveValue();
                if (reserves > 0.0) {
                    double increment = Math.min(reserves,
                            Math.min(firm.getValue() - updatedLoanDemand.get(firm.getKey()),
                                    bank.getValue() - updatedLoanSupply.get(bank.getKey())));
                    updatedLoanDemand.put(firm.getKey(), updatedLoanDemand.get(firm.getKey()) + increment);
                    updatedLoanSupply.put(bank.getKey(), updatedLoanSupply.get(bank.getKey()) + increment);
                    loanSupplies.put(bank.getKey(), loanSupplies.get(bank.getKey()) - increment); //legacy
                    loanAggregator.establishNew(firm.getKey(), bank.getKey(), increment);
                } else {
                    // leverage circle in case lender != borrower's depositor - try all (other) banks
                    final Iterator<Entry<String, Double>> otherBankIter = loanSuppliesCopy.entrySet()
                            .iterator();
                    while (otherBankIter.hasNext()) {
                        Entry<String, Double> otherBank = otherBankIter.next();
                        while (updatedLoanDemand.get(firm.getKey()) < firm.getValue()
                                && updatedLoanSupply.get(otherBank.getKey()) < otherBank.getValue()) {
                            reserves = ((Bank) lenders.get(otherBank.getKey())).getCashReserveValue();
                            if (reserves > 0.0) {
                                double increment = Math.min(reserves, Math.min(
                                        firm.getValue() - updatedLoanDemand.get(firm.getKey()),
                                        otherBank.getValue() - updatedLoanSupply.get(otherBank.getKey())));
                                updatedLoanDemand.put(firm.getKey(),
                                        updatedLoanDemand.get(firm.getKey()) + increment);
                                updatedLoanSupply.put(otherBank.getKey(),
                                        updatedLoanSupply.get(otherBank.getKey()) + increment);
                                loanSupplies.put(otherBank.getKey(),
                                        loanSupplies.get(otherBank.getKey()) - increment); //legacy
                                loanAggregator.establishNew(firm.getKey(), otherBank.getKey(), increment);
                            } else
                                break;
                        }
                        if (updatedLoanDemand.get(firm.getKey()) >= firm.getValue())
                            break; // otherBank loop shortcut
                    }
                    // in case cash is not flowing back to any bank, bank has to handle cash flow exception
                    double increment = firm.getValue() - updatedLoanDemand.get(firm.getKey());
                    if (increment > 0) {
                        updatedLoanDemand.put(firm.getKey(), updatedLoanDemand.get(firm.getKey()) + increment);
                        updatedLoanSupply.put(bank.getKey(), updatedLoanSupply.get(bank.getKey()) + increment);
                        loanSupplies.put(bank.getKey(), loanSupplies.get(bank.getKey()) - increment); //legacy
                        loanAggregator.establishNew(firm.getKey(), bank.getKey(), increment);
                    }
                    break; // no point of trying same bank again
                }
            }
            if (updatedLoanDemand.get(firm.getKey()) >= firm.getValue())
                break; // bank loop shortcut
        }
    }

    double effectiveLoan = 0., tradeWeightedInterestRate = 0.;
    int numberOfLoansCreated = 0;
    for (Stack<Loan> loans : loanAggregator.newLoanContracts.values()) {
        for (Loan loan : loans) {
            effectiveLoan += loan.getLoanPrincipalValue();
            tradeWeightedInterestRate += loan.getLoanPrincipalValue() * loan.getInterestRate();
        }
        numberOfLoansCreated += loans.size();
    }
    System.out.println("Number of loans created: " + numberOfLoansCreated + ".");
    loanAggregator.newLoanContracts.clear();
    return new Pair<Double, Double>(effectiveLoan, tradeWeightedInterestRate / effectiveLoan);
}

From source file:ch.algotrader.service.PortfolioServiceImpl.java

/**
 * {@inheritDoc}/*from w ww. j  a v a  2s.  c  o  m*/
 */
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void restorePortfolioValues(final Strategy strategy, final Date fromDate, final Date toDate) {

    Validate.notNull(strategy, "Strategy is null");
    Validate.notNull(fromDate, "From date is null");
    Validate.notNull(toDate, "To date is null");

    // delete existing portfolio values;
    List<PortfolioValue> portfolioValues = this.portfolioValueDao.findByStrategyAndMinDate(strategy.getName(),
            fromDate);

    if (portfolioValues.size() > 0) {

        this.portfolioValueDao.deleteAll(portfolioValues);

        // need to flush since new portfoliovalues will be created with same date and strategy
        this.sessionFactory.getCurrentSession().flush();
    }

    // init cron
    CronSequenceGenerator cron = new CronSequenceGenerator("0 0 * * * 1-5", TimeZone.getDefault());

    // group PortfolioValues by strategyId and date
    Map<MultiKey<Long>, PortfolioValue> portfolioValueMap = new HashMap<>();

    // create portfolioValues for all cron time slots
    Date date = cron.next(DateUtils.addHours(fromDate, -1));
    while (date.compareTo(toDate) <= 0) {

        PortfolioValue portfolioValue = getPortfolioValue(strategy.getName(), date);
        if (portfolioValue.getNetLiqValueDouble() == 0) {
            date = cron.next(date);
            continue;
        } else {
            MultiKey<Long> key = new MultiKey<>(strategy.getId(), date.getTime());
            portfolioValueMap.put(key, portfolioValue);

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("processed portfolioValue for {} {}", strategy.getName(), date);
            }

            date = cron.next(date);
        }
    }

    // save values for all cashFlows
    List<Transaction> transactions = this.transactionDao.findCashflowsByStrategyAndMinDate(strategy.getName(),
            fromDate);
    for (Transaction transaction : transactions) {

        // only process performanceRelevant transactions
        if (!transaction.isPerformanceRelevant()) {
            continue;
        }

        // do not save before fromDate
        if (transaction.getDateTime().compareTo(fromDate) < 0) {
            continue;
        }

        // if there is an existing PortfolioValue, add the cashFlow
        MultiKey<Long> key = new MultiKey<>(transaction.getStrategy().getId(),
                transaction.getDateTime().getTime());
        if (portfolioValueMap.containsKey(key)) {
            PortfolioValue portfolioValue = portfolioValueMap.get(key);
            if (portfolioValue.getCashFlow() != null) {
                portfolioValue.setCashFlow(portfolioValue.getCashFlow().add(transaction.getGrossValue()));
            } else {
                portfolioValue.setCashFlow(transaction.getGrossValue());
            }
        } else {
            PortfolioValue portfolioValue = getPortfolioValue(transaction.getStrategy().getName(),
                    transaction.getDateTime());
            portfolioValue.setCashFlow(transaction.getGrossValue());
            portfolioValueMap.put(key, portfolioValue);
        }

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("processed portfolioValue for {} {} cashflow {}", transaction.getStrategy().getName(),
                    transaction.getDateTime(), transaction.getGrossValue());
        }
    }

    // perisist the PortfolioValues
    this.portfolioValueDao.saveAll(portfolioValueMap.values());
}