1   /**
2    * Investor, the open-source investment library
3    *
4    * (C) Copyright 2008, by individual contributors as indicated by the @author tag.
5    *
6    * This library is free software; you can redistribute it and/or modify it
7    * under the terms of the GNU Lesser General Public License as
8    * published by the Free Software Foundation; either version 2.1 of
9    * the License, or (at your option) any later version.
10   *
11   * This software is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   * Lesser General Public License for more details.
15   *
16   * You should have received a copy of the GNU Lesser General Public
17   * License along with this software; if not, write to the Free
18   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
19   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
20   */
21  package com.nickokiss.investor.calc;
22  
23  import java.math.BigDecimal;
24  
25  import com.nickokiss.investor.fin.element.Bond;
26  import com.nickokiss.investor.fin.element.FinElement;
27  import com.nickokiss.investor.fin.element.Portfolio;
28  
29  /**
30   * 
31   * @author Tomasz Koscinski <tomasz.koscinski@nickokiss.com>
32   */
33  public class PortfolioCalc {
34  
35    private MathCalc mathCalc = new MathCalc();
36    
37    /**
38     * <pre>
39     * P = P1 + P2 + P3 + ... + PN
40     * </pre> 
41     */
42    public BigDecimal getPrice(Portfolio portfolio) {
43      BigDecimal portfolioPrice = mathCalc.ZERO;
44      BondCalc bondCalc = new BondCalc();
45      for (FinElement bond1 : portfolio.getFinElements()) {
46        Bond bond = (Bond) bond1;
47        BigDecimal bondPrice = bondCalc.getCurrentPrice(bond, bond.getYield());
48        portfolioPrice = portfolioPrice.add(bondPrice);
49      }
50      return portfolioPrice;
51    }
52  
53    /**
54     * <pre>
55     * D = D1*(P1/P) + D2*(P2/P) + ... + DN*(PN/P)
56     * </pre>
57     */
58    public BigDecimal getDuration(Portfolio portfolio) {
59      BigDecimal portfolioPrice = getPrice(portfolio);
60      BigDecimal portfolioDuration = mathCalc.ZERO;
61      BondCalc bondCalc = new BondCalc();
62      for (FinElement bond : portfolio.getFinElements()) {
63        Bond bond1 = (Bond) bond;
64        BigDecimal bondPrice = bondCalc.getCurrentPrice(bond1, bond1.getYield());
65        BigDecimal bondDuration = bondCalc.getMacaulayDuration(bond1);
66        BigDecimal element = bondDuration.multiply(mathCalc.div(bondPrice, portfolioPrice));
67        portfolioDuration = portfolioDuration.add(element);
68      }
69      return portfolioDuration;
70    }
71  
72  }