Strategy
A Cerebro instance is the pumping heart and controlling brain of backtrader. A Strategy is the same for the platform user.
Cerebro 만큼 Strategy 도 중요하다
설정과정
- Conception: __init__ - indicator 와 attribute 를 위한 곳
- Birth: start - Cerebro 가 Strategy 에게 시작하라고 말해주는것
- Childhood: prenext - next 가 시작하기전에 next 에 들어갈것들이 맞는지 확인
- Adulthood: next - qbuffer 체계로써 prenext -> next 로 스위칭해 들어가진다.
- Reproduction: None - 재 발급 안함 (optimazing 할때 system 에서는 함)
- Death: stop - Strategy 에게 reset 하게 하거나, 오더내려져 있는것을 걷는 과정
알림설정
- notify_order(order)
- notify_trade(trade)
- notify_cashvalue(cash, value)
- notify_fund(cash, value, fundvalue, shares)
- notify_store(msg, *args, **kwargs)
How to Buy/Sell/Close
- buy(data=None, size=None, price=None, plimit=None, exectype=None, valid=None, tradeid=0, oco=None, trailamount=None, trailpercent=None, parent=None, transmit=True, **kwargs)
- sell(data=None, size=None, price=None, plimit=None, exectype=None, valid=None, tradeid=0, oco=None, trailamount=None, trailpercent=None, parent=None, transmit=True, **kwargs)
- close(data=None, size=None, **kwargs)
Paremeter
- data (default: None) - 어떤 데이터로 거래될지 표기 , self.datas[0] or self.data0 가 default
- size (default: None) - 오더에 사용될 데이터의 사이즈 (None 일시 get_sizer()에서 size 구해옴)
- price (default: None) - 지정가 설정 (라이브에서는 tick size minimum 에 의해 사용 x 권고)
- plimit (default: None) - price 가 지정되었을때 stoplimit 오더 설정
- exectype (default: None)
- Order.Market or None - 시장가 전략, backtesting 때는 next bar 의 opening price 로 거래
- Order.Limit - 지정가에 올때만 거래가능하게 하거나 다른 limit 설정
- Order.Stop - 시장가 전략 이나 지정가 전략에 따른 거래 중지
- Order.StopLimit - pricelimit 에 다를때 오더 Stoplimit
- valid (default: None)
- None: order - 만료 설정 안함, broker 가 자체 설정 하긴 하지만 쓸모없음
- datetime.datetime or datetime.date instance - 주어진 datetime 까지 오더 가능
- Order.DAY or 0 or timedelta() - 데이 트레이딩일때 세션 끝날때까지 유효한 date 설정
- numeric value
- tradeid (default: 0) - 자산에 붙는 index, 알림이 바뀔때 strategy 에게 다시보내진다 (for opt analyze)
- **kwargs - extra parameters 가능
- orderId
- Action - 'B' or 'S'
- Size
- Lmt Price - limit price
- Aux Price - trigger price
- OrderType
- Order.Market : bytes('MKT')
- Order.Limit: bytes('LMT')
- Order.Close: bytes('MOC')
- Order.Stop: bytes('STP')
- rder.StopLimit: bytes('STPLMT')
- Order.StopTrail: bytes('TRAIL')
- Order.StopTrailLimit: bytes('TRAIL LIMIT')
- Tif (Time in Force) - Time In Force: DAY, GTC, IOC, GTD
- 'GTC' - Good til cancelled
- 'GTD' - Good til date
- GoodTillDate
- OCA - 남아있는 오더 취소 및 차단
orderType='LIT', lmtPrice=10.0, auxPrice=9.8
Bracket Orders
여러개의 오더(Market, Limit, Close, Stop, StopLimit, StopTrail, StopTrailLimit, OCO)를 한번에 할수 있는 전략으로 main side 와 children side 로 나뉘어진다.
- buy_bracket(data=None, size=None, price=None, plimit=None, exectype=2, valid=None, tradeid=0, trailamount=None, trailpercent=None, oargs={}, stopprice=None, stopexec=3, stopargs={}, limitprice=None, limitexec=2, limitargs={}, **kwargs)
- sell_bracket(data=None, size=None, price=None, plimit=None, exectype=2, valid=None, tradeid=0, trailamount=None, trailpercent=None, oargs={}, stopprice=None, stopexec=3, stopargs={}, limitprice=None, limitexec=2, limitargs={}, **kwargs)
- 설정과정
- 여러개의 오더가 제출되어진다
- main order 를 제외한 order 들은 main side 의 children 이 된다
- children side 는 main side 가 실행되어져야지만 실행되어진다
- children side 는 main side 가 취소되면 같이 취소되어진다
- children side 에 속해있는 side 가 취소될시 모든 children side 는 취소되어진다.
- For more detail <Click>
Rebalance
리밸런싱 목표(target) 의 size,value, percent 로 Portfolio Rebalancing 가능
- order_target_size(data=None, target=0, **kwargs)
- 방법
- If target > pos.size -> (buy) target - pos.size
- If target < pos.size -> (sell) pos.size - target
- target == position.size -> (None)
- 방법
- order_target_value(data=None, target=0.0, price=None, **kwargs)
- 방법
- If no target then (close postion) on data
- If target > value then (buy) on data
- If target < value then (sell) on data
- (None) if no order has been issued
- 방법
- order_target_percent(data=None, target=0.0, **kwargs)
- Example
- target=0.05 and portfolio value is 100
- The value to be reached is 0.05 * 100 = 5
- 5 is passed as the target value to order_target_value
- 방법
- If target > value
- (buy) if pos.size >= 0 (Increase a long position)
- (sell) if pos.size < 0 (Increase a short position)
- If target < value
- (sell) if pos.size >= 0 (Decrease a long position)
- (buy) if pos.size < 0 (Decrease a short position)
- (None) if no order has been issued (target == position.size)
- If target > value
- for more detail <Click>
- Example
Function
- getsizer() - size 제공
- setsizer(sizer) - default sizer 바꾸기
- getsizing(data=None, isbuy=True) - 현재 상황에서의 size 제공
- getposition(data=None, broker=None) - 주어진 broker 에 주어진 data 에서의 현재 position 제공
- getpositionbyname(name=None, broker=None) - name 으로 positon 제공
- getdatanames() - 존재하는 데이터 들의 name 을 리스트로 제공
- getdatabyname(name) - cerebro 환경을 이용하여 주어진 name 제공
Strategy with Signals
- Instead of writing a Strategy class, instantiating Indicators, writing the buy/sell logic …
- The end user add Signals (indicators anyhow) and the rest is done in the background
- Signal 만 넣어주면 알아서 buy, sell 해주는 기능
- 방법 (queried with signal[0])
- > 0 -> long indication
- < 0 -> short indication
- == 0 -> No indication
- 구조
- Main Group
- LONGSHORT: both (long) and (short) indications from this signal are taken
- LONG:
- (long indications) are taken to go long
- (short indications) are taken to close the long position. But:
- If a LONGEXIT (see below) signal is in the system it will be used to exit the long
- If a SHORT signal is available and no LONGEXIT is available , it will be used to close a long before opening a short
- SHORT:
- short indications are taken to go short
- long indications are taken to close the short position. But:
- If a SHORTEXIT (see below) signal is in the system it will be used to exit the short
- If a LONG signal is available and no SHORTEXIT is available , it will be used to close a short before opening a long
- Exit Group:
- LONGEXIT: short indications are taken to exit long positions
- SHORTEXIT: long indications are taken to exit short positions
- Order Issuing
- Orders execution type is Market and validity is None (Good until Canceled)
- Main Group
- Quick Start
- (Long indication) if the close price is above a Simple Moving Average
- (Short indication) if the close price is below a Simple Moving Average
class SMAExitSignal(bt.Indicator):
lines = ('signal',)
params = (('p1', 5), ('p2', 30),)
def __init__(self):
sma1 = bt.indicators.SMA(period=self.p.p1)
sma2 = bt.indicators.SMA(period=self.p.p2)
self.lines.signal = sma1 - sma2
- Accumulation and Order Concurrency
- Accumulation: even if already in the market, the signals would produce new orders which would increase the possition in the market
- Concurrency: new orders would be generated without waiting for the execution of other orders
- cerebro.signal_accumulate(True) (or False to re-disable it)
- cerebro.signal_concurrency(True) (or False to re-disable it)
- for more detail <Click>
Reference :
https://www.backtrader.com/docu/strategy/
Strategy - Backtrader
Strategy A Cerebro instance is the pumping heart and controlling brain of backtrader. A Strategy is the same for the platform user. The Strategy’s expressed lifecycle in methods Note A strategy can be interrupted during birth by raising a StrategySkipErr
www.backtrader.com
https://www.backtrader.com/docu/signal_strategy/signal_strategy/
Strategy - Signals - Backtrader
Strategy with Signals Operating backtrader is also possible without having to write a Strategy. Although this is the preferred way, due to the object hierarchy which makes up the machinery, using Signals is also possible. Quick summary: Instead of writing
www.backtrader.com
https://www.backtrader.com/docu/strategy-reference/
Strategy - Reference - Backtrader
Strategies Reference Reference for the built-in strategies MA_CrossOver Alias: This is a long-only strategy which operates on a moving average cross Note: Buy Logic: * No position is open on the data * The `fast` moving averagecrosses over the `slow` strat
www.backtrader.com
https://www.backtrader.com/blog/2019-07-19-rebalancing-conservative/rebalancing-conservative/
Rebalancing - Conservative Formula - Backtrader
Rebalancing with the Conservative Formula The Conservative Formula approach is presented in this paper: The Conservative Formula in Python: Quantitative Investing made Easy It is one many possible rebalancing approaches, but one that is easy to grasp. A su
www.backtrader.com
https://www.backtrader.com/blog/posts/2017-04-01-bracket/bracket/
Bracket Orders - Backtrader
Bracket Orders Release 1.9.37.116 adds bracket orders giving a very broad spectrum of orders which are supported by the backtesting broker (Market, Limit, Close, Stop, StopLimit, StopTrail, StopTrailLimit, OCO) Note This is implemented for backtesting and
www.backtrader.com
https://zhuanlan.zhihu.com/p/338720130
backtrader框架重解读九——高等动物strategy
在backtrader中,最灵活,也是最重要的一个类就是策略类。所以策略类的复杂度比中等动物有上了一个层级。(代码部分较多,如果觉得长,读者只需要读解读部分即可) 架构初思考策略类最重
zhuanlan.zhihu.com
'금융공학 > BackTrader 공부' 카테고리의 다른 글
BackTrader 5 : Indicators (0) | 2021.12.29 |
---|---|
BackTrader 1 : Concepts (0) | 2021.12.24 |
BackTrader 3 : DataFeed (0) | 2021.12.21 |
BackTrader 2 : Cerebro (0) | 2021.12.19 |
BackTrader 0 : Introduce (0) | 2021.12.19 |