1/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
3/*
4 Copyright (C) 2004, 2008 StatPro Italia srl
5 Copyright (C) 2004 Decillion Pty(Ltd)
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/exchangerate.hpp>
22
23namespace QuantLib {
24
25 Money ExchangeRate::exchange(const Money& amount) const {
26 switch (type_) {
27 case Direct:
28 if (amount.currency() == source_)
29 return Money(amount.value()*rate_, target_);
30 else if (amount.currency() == target_)
31 return Money(amount.value()/rate_, source_);
32 else
33 QL_FAIL("exchange rate not applicable");
34 case Derived:
35 if (amount.currency() == rateChain_.first->source() ||
36 amount.currency() == rateChain_.first->target())
37 return rateChain_.second->exchange(
38 amount: rateChain_.first->exchange(amount));
39 else if (amount.currency() == rateChain_.second->source() ||
40 amount.currency() == rateChain_.second->target())
41 return rateChain_.first->exchange(
42 amount: rateChain_.second->exchange(amount));
43 else
44 QL_FAIL("exchange rate not applicable");
45 default:
46 QL_FAIL("unknown exchange-rate type");
47 }
48 }
49
50 ExchangeRate ExchangeRate::chain(const ExchangeRate& r1,
51 const ExchangeRate& r2) {
52 ExchangeRate result;
53 result.type_ = Derived;
54 result.rateChain_ = std::make_pair(
55 x: ext::make_shared<ExchangeRate>(args: r1),
56 y: ext::make_shared<ExchangeRate>(args: r2));
57 if (r1.source_ == r2.source_) {
58 result.source_ = r1.target_;
59 result.target_ = r2.target_;
60 result.rate_ = r2.rate_/r1.rate_;
61 } else if (r1.source_ == r2.target_) {
62 result.source_ = r1.target_;
63 result.target_ = r2.source_;
64 result.rate_ = 1.0/(r1.rate_*r2.rate_);
65 } else if (r1.target_ == r2.source_) {
66 result.source_ = r1.source_;
67 result.target_ = r2.target_;
68 result.rate_ = r1.rate_*r2.rate_;
69 } else if (r1.target_ == r2.target_) {
70 result.source_ = r1.source_;
71 result.target_ = r2.source_;
72 result.rate_ = r1.rate_/r2.rate_;
73 } else {
74 QL_FAIL("exchange rates not chainable");
75 }
76 return result;
77 }
78
79}
80

source code of quantlib/ql/exchangerate.cpp

Morty Proxy This is a proxified and sanitized view of the page, visit original site.