Coverage Report

Created: 2025-12-08 06:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/quantlib/ql/time/daycounters/yearfractiontodate.cpp
Line
Count
Source
1
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
3
/*
4
 Copyright (C) 2023 Klaus Spanderen
5
6
 This file is part of QuantLib, a free-software/open-source library
7
 for financial quantitative analysts and developers - http://quantlib.org/
8
9
 QuantLib is free software: you can redistribute it and/or modify it
10
 under the terms of the QuantLib license.  You should have received a
11
 copy of the license along with this program; if not, please email
12
 <quantlib-dev@lists.sf.net>. The license is also available online at
13
 <https://www.quantlib.org/license.shtml>.
14
15
 This program is distributed in the hope that it will be useful, but WITHOUT
16
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17
 FOR A PARTICULAR PURPOSE.  See the license for more details.
18
*/
19
20
#include <ql/math/comparison.hpp>
21
#include <ql/time/daycounters/yearfractiontodate.hpp>
22
23
#include <boost/numeric/conversion/cast.hpp>
24
#include <cmath>
25
26
namespace QuantLib {
27
28
    Date yearFractionToDate(
29
0
        const DayCounter& dayCounter, const Date& referenceDate, Time t) {
30
0
        Date guessDate = referenceDate
31
0
            + Period(boost::numeric_cast<Integer>(round(t * 365.25)), Days);
32
0
        Time guessTime = dayCounter.yearFraction(referenceDate, guessDate);
33
34
0
        guessDate += Period(boost::numeric_cast<Integer>(
35
0
            round((t - guessTime)*365.25)), Days);
36
0
        guessTime = dayCounter.yearFraction(referenceDate, guessDate);
37
38
0
        if (close_enough(guessTime, t))
39
0
            return guessDate;
40
41
0
        const auto searchDirection = boost::numeric_cast<Integer>(copysign(1.0, t - guessTime));
42
43
0
        t += searchDirection*100*QL_EPSILON;
44
45
0
        Date nextDate;
46
0
        for (TimeUnit u: {Years, Months, Days}) {
47
0
            while (searchDirection*(
48
0
                dayCounter.yearFraction(
49
0
                    referenceDate,
50
0
                    nextDate = guessDate + Period(searchDirection, u)) - t) < 0.0)
51
0
                guessDate = nextDate;
52
0
        }
53
54
0
        guessTime = dayCounter.yearFraction(referenceDate, guessDate);
55
0
        if (close_enough(guessTime, t)
56
0
                || std::abs(dayCounter.yearFraction(referenceDate,
57
0
                    guessDate + Period(searchDirection, Days)) - t) >
58
0
                    std::abs(guessTime - t))
59
0
            return guessDate;
60
0
        else
61
0
            return guessDate + Period(searchDirection, Days);
62
0
    }
63
}
64