파이썬으로 이벤트 기반 백테스팅 - 6부

저자:선함, 2019-03-26 09:13:08, 업데이트:

이 문서는 파이썬에서 이벤트 주도 백테스터에 대한 논의를 계속합니다. 이전 기사에서는 현재 포지션을 처리하고 거래 명령을 생성하고 이익과 손실 (PnL) 을 추적하는 포트폴리오 클래스 계층을 고려했습니다.

이 기사에서는 시뮬레이션 된 주문 처리 메커니즘을 대표하는 클래스 계층을 생성하여 이러한 명령의 실행을 연구하고 궁극적으로 중개 또는 다른 시장 연결 수단에 연결합니다.

여기서 설명한 ExecutionHandler는 현재 시장 가격에 모든 주문을 채우기 때문에 매우 간단합니다. 이것은 매우 비현실적이지만 개선을위한 좋은 기준으로 사용됩니다.

이전 추상 기본 클래스 계층과 마찬가지로, 우리는 abc 라이브러리에서 필요한 속성과 장식자를 가져오야합니다. 또한 FillEvent와 OrderEvent을 가져오야합니다:

# execution.py

import datetime
import Queue

abc에서 가져오기 ABCMeta, 추상 방법

이벤트 수입에서 FillEvent, OrderEvent ExecutionHandler는 이전 추상적인 기본 클래스와 유사하며 순수 가상 메소드 execut_order를 가지고 있습니다.

# execution.py

class ExecutionHandler(object):
    """
    The ExecutionHandler abstract class handles the interaction
    between a set of order objects generated by a Portfolio and
    the ultimate set of Fill objects that actually occur in the
    market. 

    The handlers can be used to subclass simulated brokerages
    or live brokerages, with identical interfaces. This allows
    strategies to be backtested in a very similar manner to the
    live trading engine.
    """

    __metaclass__ = ABCMeta

    @abstractmethod
    def execute_order(self, event):
        """
        Takes an Order event and executes it, producing
        a Fill event that gets placed onto the Events queue.

        Parameters:
        event - Contains an Event object with order information.
        """
        raise NotImplementedError("Should implement execute_order()")

백테스트 전략을 수행하기 위해 우리는 거래가 어떻게 수행될지를 시뮬레이션해야합니다. 가능한 가장 간단한 구현은 모든 주문이 모든 양에 대한 현재 시장 가격으로 채워진다고 가정합니다. 이것은 분명히 매우 비현실적이며 백테스트 현실주의를 개선하는 큰 부분은 미끄러짐 및 시장 영향의 더 정교한 모델을 설계하는 데서 올 것입니다.

FillEvent에 Fill_cost에 대한 값이 None (execute_order의 penultimate 줄 참조) 로 주어졌다는 점에 유의하십시오. 우리는 이미 이전 기사에서 설명된 NaivePortfolio 객체에서 채우기 비용을 처리했습니다. 더 현실적인 구현에서는 현실적인 채우기 비용을 얻기 위해 current 시장 데이터 값을 사용합니다.

저는 단순히 ARCA를 교환으로 사용했지만, 백테스팅의 목적으로 이것은 순수하게 위치 보유자입니다. 라이브 실행 환경에서 이 장소 의존성은 훨씬 더 중요할 것입니다.

# execution.py

class SimulatedExecutionHandler(ExecutionHandler):
    """
    The simulated execution handler simply converts all order
    objects into their equivalent fill objects automatically
    without latency, slippage or fill-ratio issues.

    This allows a straightforward "first go" test of any strategy,
    before implementation with a more sophisticated execution
    handler.
    """
    
    def __init__(self, events):
        """
        Initialises the handler, setting the event queues
        up internally.

        Parameters:
        events - The Queue of Event objects.
        """
        self.events = events

    def execute_order(self, event):
        """
        Simply converts Order objects into Fill objects naively,
        i.e. without any latency, slippage or fill ratio problems.

        Parameters:
        event - Contains an Event object with order information.
        """
        if event.type == 'ORDER':
            fill_event = FillEvent(datetime.datetime.utcnow(), event.symbol,
                                   'ARCA', event.quantity, event.direction, None)
            self.events.put(fill_event)

이것은 이벤트 기반 백테스터를 생성하는 데 필요한 클래스 계층을 결론 지었습니다. 다음 기사에서는 백테스트 전략에 대한 성능 메트릭의 세트를 계산하는 방법을 논의 할 것입니다.


더 많은