/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2003 Ferdinando Ametrano This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email . The license is also available online at . This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include #include namespace QuantLib { LocalVolSurface::LocalVolSurface( const Handle& blackTS, const Handle& riskFreeTS, const Handle& dividendTS, const Handle& underlying) : LocalVolTermStructure(blackTS->dayCounter()), blackTS_(blackTS), riskFreeTS_(riskFreeTS), dividendTS_(dividendTS), underlying_(underlying) { registerWith(blackTS_); registerWith(riskFreeTS_); registerWith(dividendTS_); registerWith(underlying_); } LocalVolSurface::LocalVolSurface( const Handle& blackTS, const Handle& riskFreeTS, const Handle& dividendTS, Real underlying) : LocalVolTermStructure(blackTS->dayCounter()), blackTS_(blackTS), riskFreeTS_(riskFreeTS), dividendTS_(dividendTS), underlying_(boost::shared_ptr(new SimpleQuote(underlying))) { registerWith(blackTS_); registerWith(riskFreeTS_); registerWith(dividendTS_); } void LocalVolSurface::accept(AcyclicVisitor& v) { Visitor* v1 = dynamic_cast*>(&v); if (v1 != 0) v1->visit(*this); else LocalVolTermStructure::accept(v); } Volatility LocalVolSurface::localVolImpl(Time t, Real underlyingLevel) const { Real forwardValue = underlying_->value() * (dividendTS_->discount(t, true)/ riskFreeTS_->discount(t, true)); // strike derivatives Real strike, y, dy, strikep, strikem; Real w, wp, wm, dwdy, d2wdy2; strike = underlyingLevel; y = std::log(strike/forwardValue); dy = ((y!=0.0) ? y*0.000001 : 0.000001); strikep=strike*std::exp(dy); strikem=strike/std::exp(dy); w = blackTS_->blackVariance(t, strike, true); wp = blackTS_->blackVariance(t, strikep, true); wm = blackTS_->blackVariance(t, strikem, true); dwdy = (wp-wm)/(2.0*dy); d2wdy2 = (wp-2.0*w+wm)/(dy*dy); // time derivative Real dt, wpt, wmt, dwdt; if (t==0.0) { dt = 0.0001; wpt = blackTS_->blackVariance(t+dt, strike, true); QL_ENSURE(wpt>=w, "decreasing variance at strike " << strike << " between time " << t << " and time " << t+dt); dwdt = (wpt-w)/dt; } else { dt = std::min