IPython을 설치 하고 QuantLib SWIG를 통해서 python 에서 QuantLib을 사용할수 있는 환경을 만들었으니 IPython notebook을 통해서 공부한 내용을 정리해 보기 위해서 연습한 첫날입니다.
지금까지는 맨날 설치에 관한 기고만 하다가 아주 오랜만의 내용이 들어 있는 포스트입니다.
일단 연습을 위한 강의를 하나 링크를 걸겠습니다.
http://vimeo.com/97010742
위링크는 Luigi의 블로그에서 IPython notebook 이 좋은 놈이군요 저도 연습해봐야겠습니다. 하면서 올린 동영상입니다. vimeo를 통해서 보시면 되겠습니다.
순서대로 하죠 IPython notebook 자체가 웹기반으로 움직이게 설계가 되어있는 만큼 서버를 구동해야 합니다. 말이 거창해서 서버 구동이지 ... 지난 포스트에서 IPython 설치하신데에 가셔서 ipython notebook을 실행하시면 되겠습니다.
pip를 통하여 설치하신분들은 cmd 창에 ipython notebook라고 치시면 됩니다.
anaconda를 통해서 설치를 하신분들은 시작-프로그램 에서 찾아서 ~~~
구동하면 다음과 같이 됩니다.
구동과 동시에 웹페이지 형식의 IPython notebook 이 시작 되었습니다.
목록리스트가 뜨게 되는게 ipython notebook을 구동시킨 폴더의 현재 상황을 보여줍니다. Random Number.ipynb 이라고 쓰인게 동영상속의 강좌를 수강한 결과입니다. ~~~
위 링크 강좌를 천천히 따라하세요 저와 같은 파일을 갖게 됩니다.
python의 세상은 정말 무궁무진 합니다. 열심히 합시다~~
강좌 중간에
mpl_toolkits
를 import 하는 부분이 나오는데 저도 그 모듈이 깔리지 않아서 .. 강좌를 듣다가 스톱하고는 설치 후 진행했습니다. 링크 걸어 드리겠습니다.
http://www.lfd.uci.edu/~gohlke/pythonlibs/
위 링크에서 Basemap을 검색하셔서 본인이 맞는 버젼을 설치하시면 됩니다.
mpl 이 가만 보니까 Mat Plot Lib 의 약자인가 봅니다. ㅎㅎ
감사합니다. 즐프~~
2014년 8월 28일 목요일
2014년 4월 24일 목요일
C++ 에서 QuantLib-SWIG 와 Thread-Safe 한 Observer Pattern
원문출처
http://hpcquantlib.wordpress.com/2012/02/27/quantlib-swig-and-a-thread-safe-observer-pattern-in-c/
QuantLib은 사실 Thread-Safe 하지 않습니다. 멀티코어나 병렬환경에서의 성공적인 사용은 여러 프로세스간의 message passing에 의해서 보다는 shared memory 와 multi threading 에 의해서 이루어 집니다. 만약 서로다른 thread 가 서로 다른 object에서 작동을 한다면 QuantLib 또한 Multi threading 환경에서 사용될수 있습니다.(QL_ENABLE_SESSIONS 를 정의 하는 것은 singleton을 thread에 종속적이게 만듭니다.)
만약 당신이 QuantLib을 SWIG를 통하여 Java나 Scala에서 사용한다면 설령 메인 루틴이 싱글스레드 일지라도 QuantLib 루틴은 자동적으로 multi threading 환경에서 실행되어집니다.
JVM의 가비지 컬렉터는 보통 다른 thread에서 돌고 있습니다. 이것은 QuantLib에 구현되어 있는 Observer Pattern 과 결합하여 심각한 문제를 초래 할수 있습니다. 즉, 아래의 간단한 single thread Scala 코드는 멀티코어 컴퓨터에서 짧은 시간에 충돌이 일어날수 있습니다.
가장 중요한 문제는 Observer 가 Destructor가 작용하기 전에 사용불능 상태가 되는것입니다. 이것은 이론적으로 boost::shared_ptr의 새로운 instance 마다 특수한 "삭제자(Deleter)"를 추가하는 것이지만 이것 또한 library의 아주 많은 수정을 초래합니다.
전처리 지시자 BOOST_SP_ENABLE_DEBUG_HOOKS 와 함게 컴파일을 하면 boost library는 boost의 smart pointer의 소멸자가 호출되기전에 callback hook하는 것을 추가하게 된다. 이 hook은 observer의 소멸자가 호출되기전에 observer를 사용할수 없게 하는데 사용한다. 추가적으로 boost::signals2 library [3]은 간단하고 thread-safe한 공지 메커니즘을 제공한다.
원래의 QuantLib의 observer/Observable interface에 맞춰 수정된 thread-safe 한 구현은 여기서 찾을수 있다. 모든 소스파일에 전처리지시자 BOOST_SP_ENABLE_DEBUG_HOOKS를 set 한다. QuantLib project에 observable.hpp 와 observable.cpp 파일을 교체 혹은 추가하고 QuantLib library와 QuantLib-SWIG 모듈을 다시 컴파일 한다.
http://hpcquantlib.wordpress.com/2012/02/27/quantlib-swig-and-a-thread-safe-observer-pattern-in-c/
QuantLib은 사실 Thread-Safe 하지 않습니다. 멀티코어나 병렬환경에서의 성공적인 사용은 여러 프로세스간의 message passing에 의해서 보다는 shared memory 와 multi threading 에 의해서 이루어 집니다. 만약 서로다른 thread 가 서로 다른 object에서 작동을 한다면 QuantLib 또한 Multi threading 환경에서 사용될수 있습니다.(QL_ENABLE_SESSIONS 를 정의 하는 것은 singleton을 thread에 종속적이게 만듭니다.)
만약 당신이 QuantLib을 SWIG를 통하여 Java나 Scala에서 사용한다면 설령 메인 루틴이 싱글스레드 일지라도 QuantLib 루틴은 자동적으로 multi threading 환경에서 실행되어집니다.
JVM의 가비지 컬렉터는 보통 다른 thread에서 돌고 있습니다. 이것은 QuantLib에 구현되어 있는 Observer Pattern 과 결합하여 심각한 문제를 초래 할수 있습니다. 즉, 아래의 간단한 single thread Scala 코드는 멀티코어 컴퓨터에서 짧은 시간에 충돌이 일어날수 있습니다.
import org.quantlib.{Array => QArray, _}
object ObserverTest {
def main(args: Array[String]) : Unit = {
System.loadLibrary("QuantLibJNI");
val aSimpleQuote = new SimpleQuote(0)
while (true) {
(0 until 10).foreach(_ => {
new QuoteHandle(aSimpleQuote)
aSimpleQuote.setValue(aSimpleQuote.value + 1)
})
System.gc
}
}
}
같은 객체가 동일한 시점에 aSimpleQuote.setValue 함수에 의해 update 함수가 호출될때 가비지 콜렉터는 observer의 소멸자를 호출합니다.(이 내용에 대한 QuantLib Mailing list는 여기에서 확인 할수 있습니다.). greenfield projects에서 [2]의 저자는 C++에서의 적당한 해답을 제시합니다. 안타깝게도 해당 솔루션은 QuantLib에 적용될 수 없었습니다. 해당 솔루션은 Observer pattern의 interface에 많은 변화를 주어야 하고 obsever pattern의 interface의 변경은 QuantLib library의 아주 많은 변화를 초래하기 때문이었습니다.가장 중요한 문제는 Observer 가 Destructor가 작용하기 전에 사용불능 상태가 되는것입니다. 이것은 이론적으로 boost::shared_ptr의 새로운 instance 마다 특수한 "삭제자(Deleter)"를 추가하는 것이지만 이것 또한 library의 아주 많은 수정을 초래합니다.
전처리 지시자 BOOST_SP_ENABLE_DEBUG_HOOKS 와 함게 컴파일을 하면 boost library는 boost의 smart pointer의 소멸자가 호출되기전에 callback hook하는 것을 추가하게 된다. 이 hook은 observer의 소멸자가 호출되기전에 observer를 사용할수 없게 하는데 사용한다. 추가적으로 boost::signals2 library [3]은 간단하고 thread-safe한 공지 메커니즘을 제공한다.
원래의 QuantLib의 observer/Observable interface에 맞춰 수정된 thread-safe 한 구현은 여기서 찾을수 있다. 모든 소스파일에 전처리지시자 BOOST_SP_ENABLE_DEBUG_HOOKS를 set 한다. QuantLib project에 observable.hpp 와 observable.cpp 파일을 교체 혹은 추가하고 QuantLib library와 QuantLib-SWIG 모듈을 다시 컴파일 한다.
[1] Simplified Wrapper and Interface Generator, SWIG
[2] Shuo Chen, Where Destructors meet Threads
[3] Douglas G., Mori Hess F., Boost.Signals2
2014년 4월 22일 화요일
Multi-Threading 과 Quantlib
원문출처
http://hpcquantlib.wordpress.com/2013/07/26/multi-threading-and-quantlib/
QuantLib 자체로는 Thread-Safe 하지 않다. 하나이상의 코어에서 몇개의 독립적인 프로세스를 만드는 것이 표준이다. Ricacardo의 thread-safe 한 singleton 패치는 서로다른 스레드가 명시적으로 객체를 공유하지 않으면 Quantlib을 Multi-threading 응용프로그램에서 사용할수 있습니다. 사실 이 패치는 싱글턴 패턴을 각 스레드 로컬한 싱글턴 패턴으로 바꿔줍니다.
이패치의 사용사례중 하나는 test-suite를 Muliti-threading 환경에서 테스트해보는 것입니다. 예를들어 i7 3.2Ghz 쿼드코어에 하이퍼스레딩 코어 4개를 합한 환경에서 약 8분이 걸리던 작업이 2분정도 걸리게 됩니다.
QuantLib을 Java/Scala/C# or F# 응용프로그램에서 SWIG Layer를 통하여 사용하는 것은 multi-threading 요구사항을 위반하는 것입니다. 왜냐하면 가비지 컬랙터가 다른 스레드에서 실행되고 QuantLib 객체가 서로 다른 쓰레드간에 공유되기 때문이다. 이것은 QuantLib 의 Observer pattern 구현에서 문제를 야기한다 이에 관한 자세한 얘기는 다음에서 다룬다.
boost::signals2 와 Riccardo의 Thread-safe singleton 패치에 기반한 observer pattern의 향상된 구현과 multi-threading test runner는 Github에서 다운 받을수 있다.
Linux/MacOS 환경에서의 사용시
윈도우 환경에서는 다음에 상응하는 전처리기를 userconfig.hpp 에 명시되어 있습니다.
이러한 작업의 이점은 Multi-threading 응용프로그램에서 서로다른 스레드 간에 SWIG/QuantLib 의 객체를 명시적으로 공유하지 않기때문에 Java/Scala/C#/F# and a thread local singleton implementation 을 위한 안정적인 SWIG Interface 입니다.
http://hpcquantlib.wordpress.com/2013/07/26/multi-threading-and-quantlib/
QuantLib 자체로는 Thread-Safe 하지 않다. 하나이상의 코어에서 몇개의 독립적인 프로세스를 만드는 것이 표준이다. Ricacardo의 thread-safe 한 singleton 패치는 서로다른 스레드가 명시적으로 객체를 공유하지 않으면 Quantlib을 Multi-threading 응용프로그램에서 사용할수 있습니다. 사실 이 패치는 싱글턴 패턴을 각 스레드 로컬한 싱글턴 패턴으로 바꿔줍니다.
이패치의 사용사례중 하나는 test-suite를 Muliti-threading 환경에서 테스트해보는 것입니다. 예를들어 i7 3.2Ghz 쿼드코어에 하이퍼스레딩 코어 4개를 합한 환경에서 약 8분이 걸리던 작업이 2분정도 걸리게 됩니다.
QuantLib을 Java/Scala/C# or F# 응용프로그램에서 SWIG Layer를 통하여 사용하는 것은 multi-threading 요구사항을 위반하는 것입니다. 왜냐하면 가비지 컬랙터가 다른 스레드에서 실행되고 QuantLib 객체가 서로 다른 쓰레드간에 공유되기 때문이다. 이것은 QuantLib 의 Observer pattern 구현에서 문제를 야기한다 이에 관한 자세한 얘기는 다음에서 다룬다.
boost::signals2 와 Riccardo의 Thread-safe singleton 패치에 기반한 observer pattern의 향상된 구현과 multi-threading test runner는 Github에서 다운 받을수 있다.
Linux/MacOS 환경에서의 사용시
./configure --enable-tss --enable-thread-safe-observer-patternthread-safe singleton 과 thread-safe observer pattern을 사용할수 있게 한다.
윈도우 환경에서는 다음에 상응하는 전처리기를 userconfig.hpp 에 명시되어 있습니다.
#define QL_ENABLE_TSS #define QL_ENABLE_THREAD_SAFE_OBSERVER_PATTERNboost::shared_ptr의 후크를 변화시키기 위해 다음 파일에서 전처리지시자 BOOST_SP_ENABLE_DEBUG_HOOKS 를 BOOST_SP_ENABLE_DEBUG_HOOKS_2 로 변경합니다.
boost/smart_ptr/detail/sp_counted_impl.hpp
배경 : 원래의 전처리지시자인 BOOST_SP_ENABLE_DEBUG_HOOKS 은 shared_ptr의 메모리 레이아웃을 변경하는 것이 다른 미리 컴파일된 shared_ptr을 사용하는 라이브러리와 문제를 일으킬수 있습니다.이러한 작업의 이점은 Multi-threading 응용프로그램에서 서로다른 스레드 간에 SWIG/QuantLib 의 객체를 명시적으로 공유하지 않기때문에 Java/Scala/C#/F# and a thread local singleton implementation 을 위한 안정적인 SWIG Interface 입니다.
2014년 3월 25일 화요일
QuantLib 분석하기 - RelativeDateBootstrapHelper
현재 게재 중인 QuantLib 포스트의 목표는 Bond.cpp 예제에 나오는 Curve Construction의 구조의 이해임을 밝힙니다.
RelativeDateBootstrapHelper class 의 존재의 이유는 다음 comment에서 너무 확실해 졌습니다.
global evaluation date와 date schedule 을 잘 이어주는 class라고 합니다.
global evaluation date가 변화 하면 date schedule을 재조정하기도 하고요.
//! Bootstrap helper with date schedule relative to global evaluation date
/*! Derived classes must takes care of rebuilding the date schedule when
the global evaluation date changes
*/
RelativeDateBootstrapHelper class의 선언부입니다. 이전 포스트에서 설명한 BootstrapHelper을 상속 받는 구조입니다.
template <class TS>
class RelativeDateBootstrapHelper : public BootstrapHelper<TS> {
public:
생성자들입니다. 생성자의 모습이 BootstrapHelper와 너무 흡사합니다.
RelativeDateBootstrapHelper(const Handle<Quote>& quote);
RelativeDateBootstrapHelper(Real quote);
//! \name Observer interface
//@{
중요한 부분입니다. RelaticeDateBootstrapHelper class의 이유이기도 하구요. Settings 객체의 evaluationDate 와 RelaticeDateBootstrapHelper class의 member 인 evaluationDate_의 날짜를 동일하게 유지하게 하고 있습니다.
void update() {
if (evaluationDate_ != Settings::instance().evaluationDate()) {
evaluationDate_ = Settings::instance().evaluationDate();
initializeDates();
}
BootstrapHelper<TS>::update();
}
//@}
protected:
Date schedule 에 대해서 날짜를 재조정 하는 함수인것 같습니다. Date Schedule의 상황에 따라서 적당한 날짜 초기화 함수를 RelaticeDateBootstrapHelper class 를 상속받는 class들에서 구현하리라 예상됩니다.
virtual void initializeDates() = 0;
Date evaluationDate_;
};
class method들에 대한 정의가 있기는 하지만 모두 constructor들이므로 생략하겠습니다.
RelativeDateBootstrapHelper class 의 존재의 이유는 다음 comment에서 너무 확실해 졌습니다.
global evaluation date와 date schedule 을 잘 이어주는 class라고 합니다.
global evaluation date가 변화 하면 date schedule을 재조정하기도 하고요.
//! Bootstrap helper with date schedule relative to global evaluation date
/*! Derived classes must takes care of rebuilding the date schedule when
the global evaluation date changes
*/
RelativeDateBootstrapHelper class의 선언부입니다. 이전 포스트에서 설명한 BootstrapHelper을 상속 받는 구조입니다.
template <class TS>
class RelativeDateBootstrapHelper : public BootstrapHelper<TS> {
public:
생성자들입니다. 생성자의 모습이 BootstrapHelper와 너무 흡사합니다.
RelativeDateBootstrapHelper(const Handle<Quote>& quote);
RelativeDateBootstrapHelper(Real quote);
//! \name Observer interface
//@{
중요한 부분입니다. RelaticeDateBootstrapHelper class의 이유이기도 하구요. Settings 객체의 evaluationDate 와 RelaticeDateBootstrapHelper class의 member 인 evaluationDate_의 날짜를 동일하게 유지하게 하고 있습니다.
void update() {
if (evaluationDate_ != Settings::instance().evaluationDate()) {
evaluationDate_ = Settings::instance().evaluationDate();
initializeDates();
}
BootstrapHelper<TS>::update();
}
//@}
protected:
Date schedule 에 대해서 날짜를 재조정 하는 함수인것 같습니다. Date Schedule의 상황에 따라서 적당한 날짜 초기화 함수를 RelaticeDateBootstrapHelper class 를 상속받는 class들에서 구현하리라 예상됩니다.
virtual void initializeDates() = 0;
Date evaluationDate_;
};
class method들에 대한 정의가 있기는 하지만 모두 constructor들이므로 생략하겠습니다.
2014년 3월 24일 월요일
QuantLib 분석하기 - BootstrapHelper
기본적으로 template Class로 구성되어 있습니다. TS는 termstructure 에 대한 class type을 나타내고 있습니다.
observer, observable pattern을 상속 받고 있습니다.
template <class TS>
class BootstrapHelper : public Observer, public Observable {
public:
생성자로는 const Handle<Quote>& 또는 Real을 받고 있습니다. 멤버 quote_ 을 채우기 위한 변수로 보입니다.
BootstrapHelper(const Handle<Quote>& quote);
BootstrapHelper(Real quote);
virtual ~BootstrapHelper() {}
//! \name BootstrapHelper interface
//@{
const Handle<Quote>& quote() const { return quote_; }
pure virtual function 입니다. 본 클래스는 abstract class가 되겠습니다. impliedQuote 이라는 이름에서 느껴지듯이 Real Quote 과 Implied Quote 사이에 괴리가 존재 할수 있습니다.
virtual Real impliedQuote() const = 0;
Real quoteError() const { return quote_->value() - impliedQuote(); }
//! sets the term structure to be used for pricing
경고를 주고 있습니다. TS 라는 Termstructure 가 rateHelper class의 whole life 동안 존재할지에 대해서 보장을 할수 없고 그런 구조는 프로그래머에게 pointer valid를 강요한다네요.
/*! \warning Being a pointer and not a shared_ptr, the term
structure is not guaranteed to remain allocated
for the whole life of the rate helper. It is
responsibility of the programmer to ensure that
the pointer remains valid. It is advised that
this method is called only inside the term
structure being bootstrapped, setting the pointer
to <b>this</b>, i.e., the term structure itself.
*/
virtual void setTermStructure(TS*);
relevant date 관련 Bootstrapping Class 를 위한 함수 입니다. 멤버 earliestDate_, latestDate_ 와 관련이 있어 보입니다. 이름만 봐도 기간의 시작을과 만기일을 알려주는 느낌이네요.
거의 모든 Curve 관련 Bootstrapping Helper class 들이 이러한 구조를 가지고 갑니다.
//! earliest relevant date
/*! The earliest date at which data are needed by the
helper in order to provide a quote.
*/
virtual Date earliestDate() const;
//! latest relevant date
/*! The latest date at which data are needed by the
helper in order to provide a quote. It does not
necessarily equal the maturity of the underlying
instrument.
*/
virtual Date latestDate() const;
//@}
//! \name Observer interface
//@{
virtual void update();
//@}
//! \name Visitability
//@{
virtual void accept(AcyclicVisitor&);
//@}
protected:
Handle<Quote> quote_;
TS* termStructure_;
Date earliestDate_, latestDate_;
};
생성자입니다. 모양이 너무 일반적이네요. 특이한점은 termStructure_에 아무것도 넣지 않는다는것이 특징입니다. 파생 클래스에서 setTermStructure 함수를 통해 채워 넣어줄모양입니다.
template <class TS>
BootstrapHelper<TS>::BootstrapHelper(const Handle<Quote>& quote)
: quote_(quote), termStructure_(0) {
registerWith(quote_);
}
template <class TS>
BootstrapHelper<TS>::BootstrapHelper(Real quote)
: quote_(Handle<Quote>(boost::shared_ptr<Quote>(new SimpleQuote(quote)))),
termStructure_(0) {}
template <class TS>
void BootstrapHelper<TS>::setTermStructure(TS* t) {
QL_REQUIRE(t != 0, "null term structure given");
termStructure_ = t;
}
template <class TS>
Date BootstrapHelper<TS>::earliestDate() const {
return earliestDate_;
}
template <class TS>
Date BootstrapHelper<TS>::latestDate() const {
return latestDate_;
}
observer, observable 을 상속 받은 만큼 update를 구현하고 있습니다.
template <class TS>
void BootstrapHelper<TS>::update() {
notifyObservers();
}
해당 클래스의 가장 이해하기 힘든 부분입니다. Visitor pattern을 사용하고 있습니다. BootstrapHelper라는 이름 답게 다양항 작업을 수행할수 있는 구조가 필요해 보입니다. 이에 대한 자세한 설명은 차후에 이 함수가 적당하게 쓰이는 부분에서 같이 하겠습니다.
template <class TS>
void BootstrapHelper<TS>::accept(AcyclicVisitor& v) {
Visitor<BootstrapHelper<TS> >* v1 =
dynamic_cast<Visitor<BootstrapHelper<TS> >*>(&v);
if (v1 != 0)
v1->visit(*this);
else
QL_FAIL("not a bootstrap-helper visitor");
}
다음엔 RelativeDateBootstrapHelper class를 분석하겠습니다.
감사합니다.
observer, observable pattern을 상속 받고 있습니다.
template <class TS>
class BootstrapHelper : public Observer, public Observable {
public:
생성자로는 const Handle<Quote>& 또는 Real을 받고 있습니다. 멤버 quote_ 을 채우기 위한 변수로 보입니다.
BootstrapHelper(const Handle<Quote>& quote);
BootstrapHelper(Real quote);
virtual ~BootstrapHelper() {}
//! \name BootstrapHelper interface
//@{
const Handle<Quote>& quote() const { return quote_; }
pure virtual function 입니다. 본 클래스는 abstract class가 되겠습니다. impliedQuote 이라는 이름에서 느껴지듯이 Real Quote 과 Implied Quote 사이에 괴리가 존재 할수 있습니다.
virtual Real impliedQuote() const = 0;
Real quoteError() const { return quote_->value() - impliedQuote(); }
//! sets the term structure to be used for pricing
경고를 주고 있습니다. TS 라는 Termstructure 가 rateHelper class의 whole life 동안 존재할지에 대해서 보장을 할수 없고 그런 구조는 프로그래머에게 pointer valid를 강요한다네요.
/*! \warning Being a pointer and not a shared_ptr, the term
structure is not guaranteed to remain allocated
for the whole life of the rate helper. It is
responsibility of the programmer to ensure that
the pointer remains valid. It is advised that
this method is called only inside the term
structure being bootstrapped, setting the pointer
to <b>this</b>, i.e., the term structure itself.
*/
virtual void setTermStructure(TS*);
relevant date 관련 Bootstrapping Class 를 위한 함수 입니다. 멤버 earliestDate_, latestDate_ 와 관련이 있어 보입니다. 이름만 봐도 기간의 시작을과 만기일을 알려주는 느낌이네요.
거의 모든 Curve 관련 Bootstrapping Helper class 들이 이러한 구조를 가지고 갑니다.
//! earliest relevant date
/*! The earliest date at which data are needed by the
helper in order to provide a quote.
*/
virtual Date earliestDate() const;
//! latest relevant date
/*! The latest date at which data are needed by the
helper in order to provide a quote. It does not
necessarily equal the maturity of the underlying
instrument.
*/
virtual Date latestDate() const;
//@}
//! \name Observer interface
//@{
virtual void update();
//@}
//! \name Visitability
//@{
virtual void accept(AcyclicVisitor&);
//@}
protected:
Handle<Quote> quote_;
TS* termStructure_;
Date earliestDate_, latestDate_;
};
생성자입니다. 모양이 너무 일반적이네요. 특이한점은 termStructure_에 아무것도 넣지 않는다는것이 특징입니다. 파생 클래스에서 setTermStructure 함수를 통해 채워 넣어줄모양입니다.
template <class TS>
BootstrapHelper<TS>::BootstrapHelper(const Handle<Quote>& quote)
: quote_(quote), termStructure_(0) {
registerWith(quote_);
}
template <class TS>
BootstrapHelper<TS>::BootstrapHelper(Real quote)
: quote_(Handle<Quote>(boost::shared_ptr<Quote>(new SimpleQuote(quote)))),
termStructure_(0) {}
template <class TS>
void BootstrapHelper<TS>::setTermStructure(TS* t) {
QL_REQUIRE(t != 0, "null term structure given");
termStructure_ = t;
}
template <class TS>
Date BootstrapHelper<TS>::earliestDate() const {
return earliestDate_;
}
template <class TS>
Date BootstrapHelper<TS>::latestDate() const {
return latestDate_;
}
observer, observable 을 상속 받은 만큼 update를 구현하고 있습니다.
template <class TS>
void BootstrapHelper<TS>::update() {
notifyObservers();
}
해당 클래스의 가장 이해하기 힘든 부분입니다. Visitor pattern을 사용하고 있습니다. BootstrapHelper라는 이름 답게 다양항 작업을 수행할수 있는 구조가 필요해 보입니다. 이에 대한 자세한 설명은 차후에 이 함수가 적당하게 쓰이는 부분에서 같이 하겠습니다.
template <class TS>
void BootstrapHelper<TS>::accept(AcyclicVisitor& v) {
Visitor<BootstrapHelper<TS> >* v1 =
dynamic_cast<Visitor<BootstrapHelper<TS> >*>(&v);
if (v1 != 0)
v1->visit(*this);
else
QL_FAIL("not a bootstrap-helper visitor");
}
다음엔 RelativeDateBootstrapHelper class를 분석하겠습니다.
감사합니다.
2014년 3월 11일 화요일
Boost 와 QuantLib 를 linux에서 설치하기
어제는 Boost를 설치하는 방법에 대해서 포스팅 했었습니다.
그런데 오늘 QuantLib.org에서 아주 간단하고도 편한 설치 법이 있네요.
Visual Studio 에서 처럼 공용설정도 할수 있더라구요.
링크는 다음과 같습니다.
1. Boost Installation
부스트를 설치하고 싶으시면 Terminal 에 다음을 입력하세요
sudo port install boost
저 같은 경우는 저 명령어가 먹지 않아서
sudo yum install boost
라는 명령어로 해결했습니다. 마찬가지로
sudo apt-get install boost
도 가능하지 않을까 싶은데요. 각자의 컴터에 맞는 설정이 있을꺼라고 생각합니다.
2. QuantLib Installation
다음 링크를 통하여 최신버젼의 QuantLib을 다운 받으세요 리눅스의 경우 당연히 확장자가 tar.gz인 파일을 다운 받으셔야 합니다.
Terminal 에 다음을 차례로 입력합니다.
tar xzvf QuantLib-1.0.1.tar.gz
cd QuantLib-1.0.1
./configure --enable-static --with-boost-include=/opt/local/include/ \
--with-boost-lib=/opt/local/lib/ --prefix=/opt/local/make && sudo make installQuantLib의 설치가 완료 될때 까지는 시간이 소요됩니다. 적당한 운동을 권유합니다.QuantLib의 올바른 설치를 확인 하기 위하여 Examples 폴더에서 다양한 Example들을 컴파일 해보세요. 예를들면g++ -I/opt/local/include/ -I/opt/local/include/boost BermudanSwaption.cpp \ -o bermudanswaption -L/opt/local/lib/ -lQuantLib위의 명령어를 입력하면 해당 폴더에 bermudanswaption이 생깁니다. 해당 파일을 실행하는 방법은./bermudanswaption입니다. 하지만 간혹 다음과 같은 에러메시지를 발견할수 있습니다.libQuantLib.so.0: cannot open shared object file: No sush file...해당에러는 링킹 에러입니다. 위의 문제의 해법은 Luigi님께서 답변해주고 계십니다.http://sourceforge.net/p/quantlib/mailman/quantlib-users/?viewmonth=201305내용을 요약하자면링커가 맛이 갔네요/etc/ld.so.conf 파일에/usr/local/lib 라고 덧붙이세요그리고는 terminal에 다음과 같이 입력하세요sudo ldconfig아마 이제 잘 돌아 갈껍니다.마지막으로 부스트를 공용속성처럼 쓰고 싶다면~/bash_profile 파일에 다음을 덧붙이세요export CPLUS_INCLUDE_PATH=/opt/local/include export C_INCLUDE_PATH=/opt/local/include export DYLD_LIBRARY_PATH=/opt/local/lib이제 부스트에 관해서는 포함(-I)이나 링크(-L)를 걸 필요가 없어졌네요 ㅎㅎ감사합니다.
피드 구독하기:
글 (Atom)


