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들이므로 생략하겠습니다.

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를 분석하겠습니다. 
감사합니다.

2014년 3월 19일 수요일

erlang 단축기 기능

erlang을 사용할때 일반적인 Prompt 와 달라서 당황할수 있게 됩니다.

앞으로 계속 이포스트는 업데이트 할 예정인데요

단축키 설명입니다.

1. erlang 끝내기

Ctrl + G -> 'q'

2. 새로운 erlang shell 실행하기

Ctrl + G -> 's' and 'c'

3. erlang variable Unbound, 변수 지우기, 언바운드 하기

f(var). : var  unbound
f().     : unbound every variable




설명이 잘못 되었으면 알려주세요~~~ 수정할께요

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 install
QuantLib의 설치가 완료 될때 까지는 시간이 소요됩니다. 적당한 운동을 권유합니다. 
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)를 걸 필요가 없어졌네요 ㅎㅎ
감사합니다.


2014년 3월 10일 월요일

Linux에 Boost 설치하기

=================================================================================
추가자료 2014년 5월 7일

Boost의 아주 간단한 설치 방법입니다. 오히려 처음부터 이렇게 포스팅 하는게 맞는가 하는 생각도 하게 만들어 주는 방법이었습니다. QuantLib을 설치하는것을 읽다가 알게 된 방법입니다.

해당 포스트는 여기에 있습니다.

위의 링크를 따라가면 부스트를 공용속성에 넣는 방법도 확인할수 있습니다.

=================================================================================

Boost 는 더이상 옵션이 아닙니다. 필수입니다.

리눅스에서 Boost를 설치하는방법입니다.

Linux 에서 Terminal 을 엽니다 (Ctrl + Alt + T)


1. 시스템을 업데이트 합니다.
sudo apt-get update

2. Boost를 다운받습니다.
wget -c 'http://sourceforge.net/projects/boost/files/boost/1.55.0/boost_1_55_0.tar.bz2/download'

3. 압축을 해제 합니다.
tar -xvf download

4. boost 폴더에 들어 갑니다.
cd boost_1_55_0

5. bootstrap shell을 실행합니다. (b2 파일이 생성됩니다.)
./bootstrap.sh

6. b2를 실행하여 설치를 시작합니다.
./b2 install

/usr/local/include
/usr/local/lib

폴더에 각각 header와 so 파일이 저장됩니다.

당연히 설정을 통해서 다른 폴더로 복사가 가능한것 같지만 .. 일단은 설치가 먼저이니

감사합니다.

AutoTools 설치방법

AutoTools 란 GNU Build System을 의미합니다. 유닉스와 비슷한 OS에서 source code를 빌드하는데 도움을 주는 프로그램 도구를 말합니다.

일반적으로 Autotools 는 GNU 에서 제공하는 utility 인 Autoconf, AutoMake, Libtool을 말합니다.

이번 포스트의 주제는 Autotools를 설치하는 방법에 대해서 포스팅 하겠습니다. 

GNU에서 꾸준히 업데이트를 해주고 있기 때문에 독자께서 읽으시는 때의 버젼은 제가 이글을 작성하는 시점보다 더 개선된 프로그램을 설치하는 것이 좋겠습니다.

프로그램의 버젼확인을 다음에서 할수 있습니다.

1. autoconf
2. automake
3. libtool

해당 루트를 통해서 파일을 다운 받을수 있습니다. 그렇다고 지금 받을 필요는 없습니다. 아래과정에서 다운로드가 포함되어 있습니다.

Linux 의 Terminal 을 엽니다 (Ctrl + Alt + T)

설치를 시작하기전에 업데이트를 합니다.

sudo apt-get update

1. autoconf 설치합니다.

wget -c 'http://ftp.gnu.org/gnu/autoconf/autoconf-2.69.tar.gz'
tar xzvf autoconf-2.69.tar.gz
cd autoconf-2.69
./configure
make && sudo make install

2. automake 설치합니다.

wget -c 'http://ftp.gnu.org/gnu/automake/automake-1.14.1.tar.gz'
tar xzvf automake-1.14.1.tar.gz
cd automake-1.14.1
./configure
make && sudo make install

3. libtool 설치합니다. 

wget -c 'http://ftp.gnu.org/gnu/libtool/libtool-2.4.2.tar.gz'
tar xzvf libtool-2.4.2.tar.gz
cd libtool-2.4.2
./configure
make && sudo make install

위에 과정을 거치면 autotools 설치가 완료 됩니다. 

오늘의 포스트를 마칩니다. 사용법은 추후에 등록하겠습니다.

생각보다 쉽지는 않네요 

2014년 3월 2일 일요일

erlang - working directory settings

erlang을 시작할때 설정파일을 통하여 working directory를 설정할수 있다.

C:\Program Files (x86)\erl5.10.4\usr\.erlang

파일을 생성한다. erlang의 버전에 따라서 폴더 이름이 간혹 달라질수 있다.

그 파일 내부에 다음과 같이 작성한다.

io:format("consulting .erlang in ~p~n",  [element(2,file:get_cwd())]).
io:format(" ______      _                   \n").
io:format("|  ____|    | |                  \n").
io:format("| |__   _ __| | __ _ _ __   __ _ \n").
io:format("|  __| | '__| |/ _` | '_ \\ / _` |\n").
io:format("| |____| |  | | (_| | | | | (_| |\n").
io:format("|______|_|  |_|\\__,_|_| |_|\\__, |\n").
io:format("                            __/ |\n").
io:format("                           |___/ \n\n").
c:cd("D:\work").


사실 처음에는 working 폴더의 위치가 "D:\work" 가 아니였지만 드라이브의 바로 하단에 위치한 폴더가 아니면 이동이 실패하는 경험을 하여서 D: 바로 밑에 폴더를 생성하였다.

2014년 3월 1일 토요일

Visual Studio 에서 pthread 사용하기

Visual Studio /Windows 에서 Pthreds에서 사용하는 방법

University of Denver의 Prof.Nathan Sturtevant 홈피를 인용합니다.

링크


해당 사용법은 이미 빌드되어진 lib, dll파일을 사용하는 방법입니다.

아래 링크를 통해서 파일을 다운 받습니다.

ftp://sourceware.org/pub/pthreads-win32/dll-latest

(이거는 아시는 분은 아시겠지만 윈도우 탐색기에 적어 넣으세요)

- include 폴더에 들어가셔서 그 폴더에 있는 모든 *.h 파일을 Visual Studio의 Include 폴더에 복붙하세요
(사실 Visual Studio의 인클루드 폴더를 지금 다운받은 폴더로 옮기면 되기는 하는데....)

- 제 컴퓨터의 include 폴더의 위치는 다음과 같습니다.
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include

- dll폴더에 들어가셔서 그 폴더에 있는 pthreadVC2.dll 파일을 VisualStudio의 bin폴더에 복붙하세요
(이것도 마찬가지죠 bin 폴더를 이폴더도 추가시키면 가능한데 ... ㅎㅎ)

- 제컴퓨터의 bin 풀더의 위치는 다음과 같습니다.
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin

- lib폴더에 들어가셔서 그 폴더에 있는 pthreadVC2.lib 파일을 VisualStudio의 lib폴더에 복붙하세요
(이것도 마찬가지죠 lib 폴더를 이폴더도 추가시키면 가능한데 ... 고만 얘기해야지.. )

- 제컴퓨터의 lib 폴더의 위치는 다음과 같습니다.
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib

- Visual Studio를 열고 플젝을 하나 실행합니다.

보기>>속성관리자 를 엽니다.

디버그 폴더를 확장합니다.

Microsoft.Cpp.Win32.user 더블클릭합니다.

공용속성 >> 링커 >> 입력

추가종속성에  pthreadVC2.lib 를 추가합니다.

완성~~