본문 바로가기

공부 : 금융공학, 금융, 통계, 공학, 경제 등

1. Class 'Strategy'

1.1. 도입.

 우선 Backtest를 위한 Strategy를 먼저 만들어 보겠다.
 Backtest는
 - 특정 전략을
 - 주어진 과거 데이터를 통해
 - 성과를 측정하는 것으로 정의할 수 있다.

 이때 성과를 측정하는 것은
 1) 매일마다 자신의 Strategy를 통해 각 자산 별 balance(잔고, 자산 A 얼마만큼, 자산 B 얼마만큼 식으로.) 조절. (년/월/일/시/분 등등 다른 단위도 가능.
 2) Historical data(과거 데이터)를 각 자산 별 balance에 대입, 각 자산별 / 자산 전체 평가액 측정.
 3) 주어진 기간동안 1)~2)를 반복. 누적된 데이터를 통해 전략의 performance 평가.

 의 식으로 이루어지므로, 성과를 측정하려면 ‘특정 전략’과 ‘주어진 과거 데이터’가 필수적이다.
 이때 ‘주어진 과거 데이터’는 searching을 통해 적당히 얻어 오면 되므로, 우린 우선 ‘특정 전략’을 구현하는 데에 초점을 맞추겠다.

1.2. Python Class에 대한 간단한 이해.
 0.의 목표를 이루기 위해서는 Class에 대한 간단한 이해가 필요하다.
 다음 문서의 7. ~ 7.5.를 읽고 오자. 아니면 구글 검색이나 책 봐도 상관없고.
https://wikidocs.net/84


1.3. Class ‘Strategy’ 정의하기.
 Class ‘Strategy’는 각 기간마다 portfolio가 어떤 행동을 취할 것인지를 기록하기 위한 Class이다. 나는 다음과 같은 방식으로 Strategy를 표현해볼 것이다.

 

주석... 달아야 하는데... ㅠㅠㅠㅠㅠ...

[전처리]

import datetime as dt
import pandas as pd
history = pd.read_excel('212DARTproject_portfolio.xlsx', index_col='Symbol')

n_asset = history.shape[1]
weights = pd.Series([1.0/n_asset for _ in range(history.shape[1])], index=history.columns)

[클래스 정의]

class Strategy:
    def __init__(self,
                 weights, # 각각의 비중, dtype : pd.Series
                 start_date, end_date, #시작일 / 종료일, dtype : datetime.date)
                 rebalance_cycle #리밸런싱 주기, dtype : int
                 ):
        self._weights = weights
        self._holdsignal = pd.Series([None for _ in weights.index], index=weights.index)
        self._start_date = start_date
        self._end_date = end_date
        self._rebalance_cycle = rebalance_cycle
        self._Decisions = None
        
    
    def make_Decisions(self):
        self._Decisions = pd.DataFrame(data = pd.Series(self._weights,
                                                       name=self._start_date) ).transpose()
        self._date = self._start_date
        self._count = self._rebalance_cycle

        while (self._date <= self._end_date):
            if (self._count == 0):
                # 나중에 strategy 종류 따라 넣을 자리
                self._weights.name = self._date
                self._Decisions = self._Decisions.append(self._weights)
                self._count = self._rebalance_cycle
            else:
                self._holdsignal.name = self._date
                self._Decisions = self._Decisions.append(self._holdsignal)

            self._date = self._date + dt.timedelta(days=1)
            self._count -= 1
           
    
    def Decisions(self):
        if self._Decisions == None:
            self.make_Decisions()
        return self._Decisions

[출력 확인]

a = Strategy(weights= weights,
             start_date=dt.date(2020,1,1),
             end_date=dt.date(2020,2,28),
             rebalance_cycle = 5)
a.Decisions()