금융공학/BackTrader 공부

BackTrader 2 : Cerebro

냥냥펀치데스 2021. 12. 19. 15:38
728x90

Cerebro achitecture

 

Cerebro

This class is the cornerstone of backtrader because it serves as a central point for:

  1. Gathering all inputs (Data Feeds), actors (Stratgegies), spectators (Observers), critics (Analyzers) and documenters (Writers) ensuring the show still goes on at any moment.
  2. Execute the backtesting/or live data feeding/trading
  3. Returning the results
  4. Giving access to the plotting facilities

Cerebro 는 BackTrader 의 엔진역할을 하며 모든 것(eg. 데이터, 전략 등등)은 Cerebro 에 연결을 하여 사용되어집니다.

실행할때도 Cerebro.run 으로 실행되며 결과도 Cerebro.plot 으로 볼수 있습니다.

 

설정 과정

더보기

1. Cerebro 생성

2. DataFeed 추가 - (Resample, Replay)

3. Strategies 추가 - (최적화)

4. 그 외 추가 - (writer, analyze, observer or observermulti)

5. Broker 추가

6. notifications 받기 

백테스트 로직

더보기

Brief outline of the flow of things:

  1. Deliver any store notifications
  2. Ask data feeds to deliver the next set of ticks/barsData Feeds are synchronized by peeking at the datetime which is going to be provided next by available data feeds.
  3. Notify the strategy about queued broker notifications of orders, trades and cash/value
  4. Tell the broker to accept queued orders and execute the pending orders with the new data
  5. Call the strategies’ next method to let the strategy evaluate the new data (and maybe issue orders which are queued in the broker)Internally the strategies will also kick the observers, indicators, analyzers and other active elements
  6. Depending on the stage it may be prenext or nextstart before the minimum period requirements of the strategy/indicators are met
  7. Tell any writers to write the data to its target

 

대기중/저장중인 notification 전달 -> Data 동기화 -> Strategy에게 broker notification(order, trades, cash/value) 전달

->  broker 에게 order 대로 거래 하게 하기 -> Strategy 의 next() 을 통해 다음 데이터 평가하게 하기 -> 그외 하기 

Function

더보기
  • addstorecb(callback) - notify_store call
  • notify_store(msg, *args, **kwargs) - notification 저장소 (data/broker/store)
  • adddatacb(callback) - notify_data call
  • notify_data(data, status, *args, **kwargs) -  - notification 데이터 (data/broker/store) <Live 모드에서 check 기능>
  • adddata(data, name=None) - data 추가 (name  지정 안할시 data._name 으로 plot 범례표시)
  • resampledata(dataname, name=None, **kwargs) - data 재구성 (**kwargs = timeframe, compression, todate)
  • replaydata(dataname, name=None, **kwargs) - system 안에서 data 재도입
  • chaindata(*args, **kwargs) - 각각의 데이터를 하나로 합치는 법 (simple)
  • rolloverdata(*args, **kwargs) - 각각의 데이터를 하나로 합치는 법 (manual change)
  • addstrategy(strategy, *args, **kwargs) - strategy 넣기
  • optstrategy(strategy, *args, **kwargs) - strategy 최적화
    • cerebro.optstrategy(MyStrategy, period=(15, 25)) or period=range(15, 25)
    • execute MyStrategy with period values 15 -> 25 (25 not included)
  • optcallback(cb) - optstrategy result call
  • addindicator(indcls, *args, **kwargs) - indicatior 추가 (run() 타임에 strategies 로 넘김)
  • addobserver(obscls, *args, **kwargs) - observer 추가 (run() 타임에 실행)
  • addobservermulti(obscls, *args, **kwargs) - multi observer 추가 (run() 타임에 실행)
    • 각각의 데이터마다 한개씩 생성됨
    • 각각의 데이터에 buy/sell observer 생성
  • addanalyzer(ancls, *args, **kwargs) - analyzer 추가 (run() 타임에 실행)
  • addwriter(wrtcls, *args, **kwargs) - writer추가 (run() 타임에 실행)
  • run(**kwargs)
    • For No Optimization: a list contanining instances of the Strategy classes added with addstrategy
    • For Optimization: a list of lists which contain instances of the Strategy classes added with addstrategy
  • runstop() - 문제 발생시 멈춤
  • setbroker(broker) - Sets a specific broker
  • getbroker() - broker 불러오기 (broker name 으로 property 간섭 가능)
  • plot(plotter=None, numfigs=1, iplot=True, start=None, end=None, width=16, height=9, dpi=300, tight=True, use=None, **kwargs)
    • If plotter is None a default Plot instance is created and kwargs are passed to it during instantiation.iplot: if True and running in a notebook the charts will be displayed inlinestart: An index to the datetime line array of the strategy or a datetime.date, datetime.datetime instance indicating the start of the plotwidth: in inches of the saved figuredpi: quality in dots per inches of the saved figure
    • tight: only save actual content and not the frame of the figure
    • height: in inches of the saved figure
    • end: An index to the datetime line array of the strategy or a datetime.date, datetime.datetime instance indicating the end of the plot
    • use: set it to the name of the desired matplotlib backend. It will take precedence over iplot
    • numfigs split the plot in the indicated number of charts reducing chart density if wished
  • addsizer(sizercls, *args, **kwargs) - Sizer 추가
  • addsizer_byidx(idx, sizercls, *args, **kwargs) - index 별 Sizer 추가
  • add_signal(sigtype, sigcls, *sigargs, **sigkwargs) - Signal Strategy 추가
  • signal_concurrent(onoff) - signal order 를 전 order 기다릴 필요 없이 하게 하는 기능
  • signal_accumulate(onoff) - 전 order 상관없이 position 확장
  • signal_strategy(stratcls, *args, **kwargs) - signal strategy 추가
  • addcalendar(cal) - 캘린더 추가 <주말,공휴일 등 추가> 
  • addtz(tz) - Timezone 추가
  • add_timer(when, offset=datetime.timedelta(0), repeat=datetime.timedelta(0), weekdays=[], weekcarry=False, monthdays=[], monthcarry=True, allow=None, tzdata=None, strats=False, cheat=False, *args, **kwargs)
    • class module 로 timer custimize 가능
    • <주식시장 시간 세팅, daily trading 세팅에 필요한 기능>
    • For more Detail <Click>
  • notify_timer(timer, when, *args, **kwargs) - add_timer 의 결과
  • add_order_history(orders, notify=True) - 오더 결과 ([datetime, size, price] or [datetime, size, price, data])

Paremeter 

더보기

 

cerebro = bt.Cerebro(**kwargs)
  • preload (default: True) - Strategy 에게 미리 데이터를 보내는 방법 
  • runonce (default: True) - Indicator 를 Vectorized mode 로 하여 batch 계산을 빠르게 하는 방법
  • live (default: False) - Live Trading 을 할때 <preload, runonce x> -> 메모리 세이빙 안됨 
  • maxcpus (default: None -> all available cores) - 몇개 코어를 사용할지
  • stdstats (default: True) - Observer (Broker (Cash and Value), Trades and BuySell) 추가
  • oldbuysell (default: False) - (False ->plot 에 매수, 매도 표시를 아래 위로 표시) (True -> 복잡한 표시) 
  • oldtrades(기본값: False) -  (False ->plot 에 매수, 매도 표시를 빨강, 파랑 삼각형) (True -> 복잡한 표시) 
  • exactbars(기본값: False) - 속도 상관없이 모든 상황을 저장하려고 할때 필요
  • tradehistory (default: False) - 모든 전략들의 이벤트 로그 표시
    • 각각의 전략 이벤트 로그 표시 -> set_tradehistory
  • writer (default: False) - 문서화 여부 -> 전략에 추가
  • optdatas (default: True) - 데이터 최적화 20% 정도 스피드 업
  • optreturn (default: True) - analyze 와 strategy 결과에 맞춰서 최적화 나머지 스킵
  • cheat_on_open (default: False) - next() 하기전에 data 의 open 과 close 중 open 을 열어서 전략 시도
    • cerebro.broker.set_coo(True) or BackBroker(coo = True) 필요
    • For more Detail <Click>
  • broker_coo (default: True) - cheat_on_open 할때 자동으로 set_coo = True 로 만들어줌
  • quicknotify (default: False) - next prices 제공전 알림 <live 할때 notification 빠르게 제공 가능> 

 

cerebro = bt.Cerebro(**kwargs)

Reference :