1/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
3/*
4 Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb
5 Copyright (C) 2005 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/methods/lattices/trinomialtree.hpp>
22#include <ql/stochasticprocess.hpp>
23
24namespace QuantLib {
25
26 TrinomialTree::TrinomialTree(
27 const ext::shared_ptr<StochasticProcess1D>& process,
28 const TimeGrid& timeGrid,
29 bool isPositive)
30 : Tree<TrinomialTree>(timeGrid.size()), dx_(1, 0.0), timeGrid_(timeGrid) {
31 x0_ = process->x0();
32
33 Size nTimeSteps = timeGrid.size() - 1;
34 QL_REQUIRE(nTimeSteps > 0, "null time steps for trinomial tree");
35
36 Integer jMin = 0;
37 Integer jMax = 0;
38
39 for (Size i=0; i<nTimeSteps; i++) {
40 Time t = timeGrid[i];
41 Time dt = timeGrid.dt(i);
42
43 //Variance must be independent of x
44 Real v2 = process->variance(t0: t, x0: 0.0, dt);
45 Volatility v = std::sqrt(x: v2);
46 dx_.push_back(x: v*std::sqrt(x: 3.0));
47
48 Branching branching;
49 for (Integer j=jMin; j<=jMax; j++) {
50 Real x = x0_ + j*dx_[i];
51 Real m = process->expectation(t0: t, x0: x, dt);
52 auto temp = Integer(std::floor(x: (m - x0_) / dx_[i + 1] + 0.5));
53
54 if (isPositive) {
55 while (x0_+(temp-1)*dx_[i+1]<=0) {
56 temp++;
57 }
58 }
59
60 Real e = m - (x0_ + temp*dx_[i+1]);
61 Real e2 = e*e;
62 Real e3 = e*std::sqrt(x: 3.0);
63
64 Real p1 = (1.0 + e2/v2 - e3/v)/6.0;
65 Real p2 = (2.0 - e2/v2)/3.0;
66 Real p3 = (1.0 + e2/v2 + e3/v)/6.0;
67
68 branching.add(k: temp, p1, p2, p3);
69 }
70 branchings_.push_back(x: branching);
71
72 jMin = branching.jMin();
73 jMax = branching.jMax();
74 }
75 }
76
77}
78
79

source code of quantlib/ql/methods/lattices/trinomialtree.cpp