1 /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 
3 /*
4  Copyright (C) 2003 Decillion Pty(Ltd)
5  Copyright (C) 2003 StatPro Italia srl
6 
7  This file is part of QuantLib, a free-software/open-source library
8  for financial quantitative analysts and developers - http://quantlib.org/
9 
10  QuantLib is free software: you can redistribute it and/or modify it
11  under the terms of the QuantLib license.  You should have received a
12  copy of the license along with this program; if not, please email
13  <quantlib-dev@lists.sf.net>. The license is also available online at
14  <http://quantlib.org/license.shtml>.
15 
16  This program is distributed in the hope that it will be useful, but WITHOUT
17  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18  FOR A PARTICULAR PURPOSE.  See the license for more details.
19 */
20 
21 #include <ql/cashflows/timebasket.hpp>
22 #include <ql/errors.hpp>
23 #include <algorithm>
24 
25 namespace QuantLib {
26 
TimeBasket(const std::vector<Date> & dates,const std::vector<Real> & values)27     TimeBasket::TimeBasket(const std::vector<Date>& dates,
28                            const std::vector<Real>& values) {
29         QL_REQUIRE(dates.size() == values.size(),
30                    "number of dates differs from number of values");
31         super& self = *this;
32         for (Size i = 0; i < dates.size(); i++)
33             self[dates[i]] = values[i];
34     }
35 
rebin(const std::vector<Date> & buckets) const36     TimeBasket TimeBasket::rebin(const std::vector<Date>& buckets) const {
37         QL_REQUIRE(!buckets.empty(), "empty bucket structure");
38 
39         std::vector<Date> sbuckets = buckets;
40         std::sort(sbuckets.begin(), sbuckets.end());
41 
42         TimeBasket result;
43 
44         for (Size i = 0; i < sbuckets.size(); i++)
45             result[sbuckets[i]] = 0.0;
46 
47         for (const_iterator j = begin(); j != end(); ++j) {
48             Date date = j->first;
49             Real value = j->second;
50             Date pDate = Null<Date>(), nDate = Null<Date>();
51 
52             std::vector<Date>::const_iterator bi =
53                 std::lower_bound(sbuckets.begin(), sbuckets.end(), date);
54 
55             if (bi == sbuckets.end())
56                 pDate = sbuckets.back();
57             else
58                 pDate = *bi;
59 
60             if (bi != sbuckets.begin() && bi != sbuckets.end())
61                 nDate = *(bi-1);
62 
63             if (pDate == date || nDate == Null<Date>()) {
64                 result[pDate] += value;
65             } else {
66                 Real pDays = Real(pDate-date);
67                 Real nDays = Real(date-nDate);
68                 Real tDays = Real(pDate-nDate);
69                 result[pDate] += value*(nDays/tDays);
70                 result[nDate] += value*(pDays/tDays);
71             }
72         }
73         return result;
74     }
75 
76 }
77 
78