본문 바로가기

주식 공부

[주식거래자동화] 08. Backtrader 활용한 주식 전략 백테스트

반응형

앞서 종목코드의 일봉데이터 정보를 사용하여 주식 전략을 백테스팅해 보려 한다.

종목 코드의 일봉데이터 저장하는 방법은 아래 링크 !

2020/12/11 - [주식 공부] - [주식거래자동화] 07. 일별거래데이터 DB 저장

 

[주식거래자동화] 07. 일별거래데이터 DB 저장

KOSPI 200 종목에 대해 KOAStudio 에서 조회한 정보를 바탕으로 DB를 생성하여 종목코드별 일봉차트를 저장한다. KOSPI 200 종목코드 받기 및 일별 데이터 조회 방법은 이전 글에 기록해 두었다. 2020/12/09

joycecoder.tistory.com

 

1. backtrader 설치

backtrader 는 백테스팅 및 거래를 위한 풍부한 기능의 파이썬 프레임 워크이다. 주식 일봉데이터와 해당 프레임워크로 매수/매도 알고리즘에 대해 수익률을 얼마나 낼 수 있는지 테스트해볼 수 있다.

 

개발 중인 Anaconda 환경에 backtrader package 를 설치하며, 아래 예제를 수행하기 위해서는 backtrader 를 이외에 추가 패키지들도 설치를 진행한다.

pip install backtrader
pip install requests
pip install matplotlib==3.2.2 # 3.2.X 버전을 설치해야만 사용 가능하다.

 

 

2. backtrader 예제

아래 예제는 backtrader 홈페이지에서 제공하는 예제이다.

www.backtrader.com/home/helloalgotrading/

 

Hello Algotrading! - Backtrader

Hello Algotrading! A classic Simple Moving Average Crossover strategy, can be easily implemented and in different ways. The results and the chart are the same for the three snippets presented below. Buy/Sell from datetime import datetime import backtrader

www.backtrader.com

from datetime import datetime
import backtrader as bt

# Create a subclass of Strategy to define the indicators and logic

class SmaCross(bt.Strategy):
    # list of parameters which are configurable for the strategy
    params = dict(
        pfast=10,  # period for the fast moving average
        pslow=30   # period for the slow moving average
    )

    def __init__(self):
        sma1 = bt.ind.SMA(period=self.p.pfast)  # fast moving average
        sma2 = bt.ind.SMA(period=self.p.pslow)  # slow moving average
        self.crossover = bt.ind.CrossOver(sma1, sma2)  # crossover signal

    def next(self):
        if not self.position:  # not in the market
            if self.crossover > 0:  # if fast crosses slow to the upside
                self.buy()  # enter long

        elif self.crossover < 0:  # in the market & cross to the downside
            self.close()  # close long position


cerebro = bt.Cerebro()  # create a "Cerebro" engine instance

# Create a data feed
data = bt.feeds.YahooFinanceData(dataname='MSFT',
                                 fromdate=datetime(2011, 1, 1),
                                 todate=datetime(2012, 12, 31))

cerebro.adddata(data)  # Add the data feed

cerebro.addstrategy(SmaCross)  # Add the trading strategy
cerebro.run()  # run it all
cerebro.plot()  # and plot it with a single command

해당 예제는 단순이동평균선(SMA)이 교차 (Cross over) 하는 시점을 활용한 매매기법을 백테스팅하는 예제이다.

 

가장 기본적으로 처음 주식을 공부하면서 봤던 가장 간단한 방식의 매매기법으로 단기 이동평균선이 장기 이동평균선을 아래에서 위로 교차하며 올라갈때 매수를 하고, 반대로 단기 이동평균선이 장기 이동평균선을 위에서 아래로 교차하며 내려갈 때 매도를 하는 방식이다.

 

예제에서는 MSFT (마이크로소프트) 종목의 2011년 1월1일 부터 2012년 12월 31일 2년간의 일봉데이터에 단기 이동평균선은 10일 기준, 장기 이동평균선은 30일 기준으로 백테스팅을한 결과이다.

 

실행 시 결과는 다음과 같다.

백테스팅한 결과 중 2번째 그래프(Trades - Net Profit/Loss) 를 보면 매도 시점의 수익률이 Negative인 결과가 대부분이며 1번째 그래프에서도 현재 Value 가 초기 자본인 10,000 보다 작은 것으로 보아 효율적인 매매 기법으로 보기 어려운 것으로 보인다.

 

위 예제는 backtrader 에서 제공하는 예제이며 실전에서 사용하면 수익을 보장할 수 없는 매매기법인게 확인이 되었다. 예제의 next 함수에서 매수/매도 하는 부분의 알고리즘 변경하거나 단기/장기 이동평균선의 기간을 달리해보는 등의 추가 예제를 실행하며 결과 확인을해 보면 도움이 될 것 같다.

 

3. DB 저장한 데이터로 Backtesting

작성중.

반응형