Etc/주식 자동 매매2022. 3. 14. 00:32
728x90

백테스트

특정 투자 전략을 과거 데이터로 검증하는 작업.

백테스트 라이브러리

1. 집라인(Zipline): 대중적으로 많이 사용, 단점 느림. Python버전 환경 영향을 탐. 참조: https://wikidocs.net/4427
   - 재정지원에 중점. 이벤트 기반

   - https://github.com/quantopian/zipline

2. 파이알고트레이드(PyAlgoTrade) (무료) : https://gbeced.github.io/pyalgotrade/

   - 문서: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/

   - 이벤트 기반

3. 트레이딩위드파이썬(TradingWithPython)

4. 파이백테스트(PyBackTest)

5. 백트레이더(BackTrader): 최근 각광, 오픈소스 기반
   https://www.backtrader.com/
 

backtrader 지원 지표 (bt.indicators 패키지)

  • Accdecoscillator
  • ATR
  • Bollinger
  • CCI
  • Crossover
  • Deviation
  • DirectionalMove
  • DMA
  • EMA
  • Ichimoku
  • MACD
  • Momentum
  • Sma
  • Stochastic
  • Willams
  • WMA

* 아래 오류 발생 시 matplotlib 버전을 3.2.2 로 재설치 한다.
pip uninstall matplotlib
pip install matplotlib==3.2.2

    from matplotlib.dates import (HOURS_PER_DAY, MIN_PER_HOUR, SEC_PER_MIN,
ImportError: cannot import name 'warnings' from 'matplotlib.dates' (/Users/jeahanjung/opt/anaconda3/envs/system_strading_py39_64/lib/python3.9/site-packages/matplotlib/dates.py)

 

import backtrader as bt
import yfinance as yf

class RsiStrategy(bt.Strategy):
    def __init__(self):
        self.rsi = bt.indicators.RSI(self.data.close)

    def next(self):
        if not self.position:
            if self.rsi < 30:
                self.order = self.buy()

        elif self.rsi > 70:
            self.order = self.sell()


cerebro = bt.Cerebro()  # create a "Cerebro" engine instance
cerebro.addstrategy(RsiStrategy)  # Add the trading strategy
# data = bt.feeds.YahooFinanceData(dataname="036570.KS", fromdate=datetime(2017, 1, 1), todate=datetime(2019, 12, 1))
data = bt.feeds.PandasData(dataname=yf.download('036570.KS', '2018-01-01', '2021-12-01'))

cerebro.adddata(data)
cerebro.broker.setcash(1000*10000) # 초기투자 금액
cerebro.addsizer(bt.sizers.SizerFix, stake=30) # 매매단위

print(f'Initial Portfolio Value : {cerebro.broker.getvalue():,.0f} KRW')
cerebro.run()  # run it all
print(f'Final Portfolio Value : {cerebro.broker.getvalue():,.0f} KRW')
cerebro.plot()  # and plot it with a sing

[*********************100%***********************]  1 of 1 completed
Initial Portfolio Value : 10,000,000 KRW
Final Portfolio Value : 12,925,000 KRW

 

728x90
Posted by 하루y