동적 프로그래밍 거래 전략


QuantStart.


빠르게 성장하는 소매점 퀀텀 트레이더 커뮤니티를 지원하는 Quantcademy 개인 회원 포털에 가입하십시오. 당신은 당신의 가장 중요한 퀀트 트레이딩 질문에 대답 할 준비가되어있는 지식이 풍부하고 마음이 맞는 퀀트 트레이더 그룹을 찾을 수 있습니다.


퀀트 트레이딩에 관한 나의 eBook을 확인해보십시오. 여기서 저는 파이썬 툴로 수익성 높은 체계적인 트레이딩 전략을 만드는 법을 가르쳐드립니다.


Python 및 R을 사용하여 시계열 분석, 기계 학습 및 베이지안 통계를 사용하는 고급 거래 전략에 관한 새로운 전자 책을 살펴보십시오.


2013 년 7 월 26 일 Michael Halls-Moore 작성


QS mailbag에서받는 가장 자주 묻는 질문 중 하나는 "알고리즘 트레이딩을위한 최고의 프로그래밍 언어는 무엇입니까?"입니다. 짧은 대답은 "최상의"언어가 없다는 것입니다. 전략 매개 변수, 성능, 모듈성, 개발, 탄력성 및 비용을 모두 고려해야합니다. 이 기사는 알고리즘 트레이딩 시스템 아키텍처의 필수 구성 요소와 구현에 관한 결정이 언어 선택에 미치는 영향을 설명합니다.


첫째, 리서치 툴, 포트폴리오 옵티 마이저, 리스크 관리자 및 실행 엔진과 같은 알고리즘 트레이딩 시스템의 주요 구성 요소를 고려합니다. 이후에 서로 다른 트레이딩 전략을 검토하고 이들이 시스템의 설계에 어떻게 영향을 주는지에 대해 조사 할 것입니다. 특히 거래 빈도와 거래량에 대해 모두 논의 할 것입니다.


거래 전략이 선택되면 전체 시스템을 설계해야합니다. 여기에는 희소하고 잠재적으로 치명적인 이벤트에 대한 하드웨어, 운영 체제 및 시스템 탄력성의 선택이 포함됩니다. 아키텍처가 고려되는 동안 연구 도구뿐 아니라 실제 실행 환경에 대해서도 성능에 대한 적절한 고려가 이루어져야합니다.


무역 시스템은 무엇을하려고합니까?


자동화 된 거래 시스템을 작성하는 "최상의"언어를 결정하기 전에 요구 사항을 정의해야합니다. 시스템이 순전히 실행 기반이 될 것입니까? 시스템에 위험 관리 또는 포트폴리오 구성 모듈이 필요합니까? 시스템에 고성능 백 테스터가 필요합니까? 대부분의 전략에서 거래 시스템은 연구 및 신호 생성이라는 두 가지 범주로 나눌 수 있습니다.


연구는 과거 데이터에 대한 전략 성과 평가와 관련이 있습니다. 이전 시장 데이터에 대한 거래 전략을 평가하는 프로세스를 백 테스팅 (backtesting)이라고합니다. 데이터 크기와 알고리즘 복잡성은 백 테스터의 계산 강도에 큰 영향을 미칩니다. CPU 속도와 동시성은 종종 연구 실행 속도를 최적화하는데있어 제한 요소입니다.


신호 생성은 알고리즘으로부터 일련의 거래 신호를 생성하고 그러한 주문을 보통 중개를 통해 시장에 보내는 것과 관련이 있습니다. 특정 전략의 경우 높은 수준의 성과가 요구됩니다. 네트워크 대역폭 및 대기 시간과 같은 I / O 문제는 종종 실행 시스템 최적화의 제한 요소입니다. 따라서 전체 시스템의 각 구성 요소에 대한 언어 선택은 상당히 다를 수 있습니다.


유형, 빈도 및 전략의 양.


채택 된 알고리즘 전략의 유형은 시스템 설계에 상당한 영향을 미칩니다. 거래되는 시장, 외부 데이터 공급 업체와의 연결성, 전략의 빈도 및 양, 개발 용이성과 성능 최적화 간의 균형, 공동 배치 된 사용자 지정을 포함한 모든 사용자 지정 하드웨어를 고려해야합니다 서버, GPU 또는 FPGA가 필요합니다.


저주파 미국 주식 전략의 기술 선택은 선물 시장에서 거래하는 고주파 통계적 재정 거래 전략의 기술 선택과 크게 다를 것입니다. 언어를 선택하기 전에 많은 데이터 공급 업체가 현재 진행중인 전략과 관련된 평가를 받아야합니다.


오프라인 상태에서 공급 업체와의 연결, API의 구조, 데이터의 적시성, 저장소 요구 사항 및 복원력을 고려해야합니다. 또한 여러 공급 업체에 신속하게 액세스 할 수있는 것이 현명합니다. 다양한 계측기에는 모두 자신 만의 스토리지 쿼크가 있으며, 여기에는 주식에 대한 여러 시세 표시와 선물에 대한 만료일이 포함됩니다 (특정 OTC 데이터는 말할 것도 없습니다). 이를 플랫폼 설계에 고려해야합니다.


전략의 빈도는 기술 스택 정의 방법의 가장 큰 동인 중 하나 일 수 있습니다. 미세하거나 두 번째 막대보다 자주 데이터를 사용하는 전략은 성과와 관련하여 중요한 고려 사항이 필요합니다.


두 번째 막대 (예 : 틱 데이터)를 초과하는 전략은 주요 요구 사항으로 실적 중심의 디자인을 유도합니다. 고 빈도 전략의 경우 상당량의 시장 데이터를 저장하고 평가해야합니다. HDF5 또는 kdb +와 같은 소프트웨어가 일반적으로 이러한 역할에 사용됩니다.


HFT 응용 프로그램에 필요한 대량의 데이터를 처리하려면 광범위하게 최적화 된 백 테스터 및 실행 시스템을 사용해야합니다. C / C ++ (일부 어셈블러 사용 가능)이 가장 강력한 언어 후보가 될 가능성이 큽니다. 초고주파 전략에는 FPGA, 교환기 위치 및 커널 / 네트워크 인터페이스 튜닝과 같은 맞춤형 하드웨어가 거의 필요합니다.


연구 시스템.


연구 시스템에는 대개 대화 형 개발과 자동화 된 스크립팅이 혼합되어 있습니다. 전자는 종종 Visual Studio, MatLab 또는 R Studio와 같은 IDE 내에서 발생합니다. 후자는 수많은 매개 변수와 데이터 포인트에 대한 광범위한 수치 계산을 포함합니다. 따라서 코드를 테스트 할 수있는 간단한 환경을 제공하는 언어 선택이 가능하지만 여러 매개 변수 차원에서 전략을 평가하는 데 충분한 성능을 제공합니다.


이 분야의 일반적인 IDE에는 광범위한 디버깅 유틸리티, "Intellisense"를 통한 코드 완성 기능 및 데이터베이스 ORM, LINQ를 통한 전체 프로젝트 스택의 간단한 개요가 포함 된 Microsoft Visual C ++ / C #, 광범위한 수치 선형 대수 및 벡터화 연산을 위해 설계된 대화식 콘솔 방식의 MatLab; R Studio는 R 통계 언어 콘솔을 본격적인 IDE에 랩핑합니다. Linux 용 Eclipse IDE Java 및 C ++; NumPy, SciPy, scikit-learn 및 pandas와 같은 데이터 분석 라이브러리를 단일 대화 형 (콘솔) 환경에 포함하는 Enthought Canopy for Python과 같은 독점적 인 IDE가 있습니다.


숫자 백 테스트의 경우 위의 모든 언어가 적합하지만 코드가 백그라운드에서 실행되므로 GUI / IDE를 사용할 필요는 없습니다. 이 단계에서 가장 중요한 고려 사항은 실행 속도입니다. 컴파일 된 언어 (예 : C ++)는 백 테스트 매개 변수 크기가 큰 경우에 유용합니다. 그러한 경우 그러한 시스템을 조심하는 것이 필요하다는 것을 기억하십시오!


Python과 같은 해석 언어는 컴파일 된 등가물과의 합리적인 수준의 경쟁력을 유지하기 위해 백 테스트 단계에서 NumPy / pandas와 같은 고성능 라이브러리를 사용합니다. 궁극적으로 백 테스팅을 위해 선택한 언어는 특정 알고리즘 요구 사항과 언어에서 사용할 수있는 라이브러리 범위 (아래에서 자세히 설명)에 따라 결정됩니다. 그러나 백 테스터 및 연구 환경에 사용되는 언어는 포트폴리오 구성, 위험 관리 및 실행 구성 요소에서 사용되는 언어와 완전히 독립적 일 수 있습니다.


포트폴리오 구축 및 리스크 관리.


포트폴리오 구성 및 위험 관리 구성 요소는 종종 소매 알고리즘 거래자에 의해 간과됩니다. 이것은 거의 항상 실수입니다. 이 도구들은 자본이 보존되는 메커니즘을 제공합니다. 그들은 "위험한"배팅의 수를 줄이려고 시도 할뿐만 아니라 거래 자체의 이탈을 최소화하여 거래 비용을 줄입니다.


이러한 구성 요소의 정교한 버전은 품질 및 일관성있는 수익성에 중요한 영향을 미칩니다. 포트폴리오 구축 메커니즘 및 리스크 관리자가 여러 시스템을 처리하기 위해 쉽게 수정 될 수 있으므로 안정적인 전략을 수립하는 것은 간단합니다. 따라서 이들은 알고리즘 거래 시스템의 설계 초기에 필수 구성 요소로 간주되어야합니다.


포트폴리오 건설 시스템의 일은 일련의 원하는 거래를 수행하고 해지를 최소화하고 다양한 요인 (예 : 부문, 자산 클래스, 변동성 등)에 대한 노출을 유지하고 다양한 자본 배분을 최적화하는 실제 거래 세트를 생성하는 것입니다 포트폴리오의 전략.


포트폴리오 구축은 종종 선형 대수 문제 (예 : 행렬 인수 분해)로 축소되므로 성능은 사용 가능한 수치 선형 대수 구현의 효율성에 크게 의존합니다. 공통 라이브러리에는 uBLAS, LAPACK 및 CAG 용 NAG가 포함됩니다. MatLab은 또한 광범위하게 최적화 된 매트릭스 연산을 보유합니다. 파이썬은 그러한 계산을 위해 NumPy / SciPy를 사용합니다. 빈번하게 재조정 된 포트폴리오는 거래 시스템에 병목 현상이 발생하지 않도록이 단계를 수행하기 위해 컴파일 된 (그리고 최적화 된!) 매트릭스 라이브러리가 필요합니다.


위험 관리는 알고리즘 거래 시스템의 또 다른 매우 중요한 부분입니다. 위험은 여러 가지 형태로 나타날 수 있습니다 : 변동성 증가 (특정 전략에서는 바람직 함), 자산 클래스, 거래 상대 디폴트, 서버 중단, "Black Swan"이벤트 및 거래 코드의 탐지되지 않은 버그 간의 상관 관계 증가, 몇 가지 예를 들자면


위험 관리 구성 요소는 과도한 변동성 및 자산 클래스와 후속 효과 간의 거래 자본에 대한 영향을 예상하고 예상합니다. 종종 이것은 Monte Carlo "스트레스 테스트"와 같은 일련의 통계 계산으로 축소됩니다. 이는 파생 상품 가격 책정 엔진의 계산 요구와 매우 유사하며 CPU와 관련이 있습니다. 이러한 시뮬레이션은 고도로 병렬 처리가 가능하며 (아래 참조) 어느 정도는 "하드웨어를 문제에 던지기"가 가능합니다.


실행 시스템.


실행 시스템의 임무는 포트폴리오 구성 및 위험 관리 구성 요소에서 필터링 된 거래 신호를 수령하여 중개 또는 기타 시장 접근 수단으로 보내는 것입니다. 대부분의 소매 알고리즘 거래 전략의 경우 인터랙티브 브로커 (Interactive Brokers)와 같은 중개 회사에 API 또는 FIX 연결이 필요합니다. 언어를 결정할 때 주요 고려 사항은 API의 품질, API의 언어 래퍼 가용성, 실행 빈도 및 예상 미끄러짐을 포함합니다.


API의 "품질"은 문서의 종류, 제공되는 성능의 종류, 액세스 할 독립형 소프트웨어가 필요한지 또는 게이트웨이가 헤드리스 방식 (즉, GUI 없음)으로 설정 될 수 있는지 여부를 나타냅니다. 대화 형 중개인의 경우 Trader WorkStation 도구는 API에 액세스하기 위해 GUI 환경에서 실행되어야합니다. 한때 데스크톱 우분투 에디션을 아마존 클라우드 서버에 설치해야만 인터랙티브 브로커에 원격으로 액세스 할 수있었습니다.


대부분의 API는 C ++ 및 / 또는 Java 인터페이스를 제공합니다. 일반적으로 C #, Python, R, Excel 및 MatLab에 대한 언어 별 래퍼를 개발하는 것은 커뮤니티의 몫입니다. 활용되는 추가 플러그인 (특히 API 래퍼)마다 버그가 시스템에 들어가는 범위가 있음에 유의하십시오. 이러한 종류의 플러그인을 항상 테스트하고 플러그인을 유지 관리해야합니다. 가치있는 계기는 최근 몇 개월 동안 코드베이스에 대한 새로운 업데이트가 몇 번 있었는지 확인하는 것입니다.


실행 빈도는 실행 알고리즘에서 가장 중요합니다. 매주 수백 건의 주문이 보내질 수 있으며 이러한 성능은 중요합니다. 부실 실행 집행 시스템을 통해 미끄러짐이 발생하며 이는 수익성에 큰 영향을 미칩니다.


일반적으로 C ++ / Java와 같은 정적 유형 언어 (아래 참조)는 일반적으로 실행하기에 최적이지만 개발 시간, 테스트 및 유지 관리 용이성이 절충됩니다. 파이썬과 펄과 같이 동적으로 유형화 된 언어는 이제 일반적으로 "충분히 빠름"입니다. 구성 요소가 모듈 방식으로 설계되어 있는지 확인하십시오 (아래 참조). 시스템 구성에 따라 구성 요소를 "교체"할 수 있습니다.


건축 계획 및 개발 프로세스.


거래 시스템의 구성 요소, 빈도 및 볼륨 요구 사항은 위에서 논의했지만 시스템 인프라는 아직 다루지 않았습니다. 소매상 인 또는 작은 펀드에서 일하는 사람들은 "많은 모자를 쓰고"있을 것입니다. 알파 모델, 위험 관리 및 실행 매개 변수, 그리고 시스템의 최종 구현을 포괄해야합니다. 특정 언어를 탐구하기 전에 최적의 시스템 아키텍처 설계가 논의 될 것입니다.


우려의 분리.


가장 먼저해야 할 가장 중요한 결정 중 하나는 거래 시스템의 "우려 사항을 어떻게 분리 할 것인가"입니다. 소프트웨어 개발에서 이것은 본질적으로 거래 시스템의 다른 측면을 개별 모듈 구성 요소로 분해하는 방법을 의미합니다.


각 구성 요소에서 인터페이스를 노출하면 외부 종속성 코드를 수정하지 않고도 성능, 안정성 또는 유지 관리를 돕는 다른 버전의 시스템 부분을 쉽게 교체 할 수 있습니다. 이러한 시스템에 대한 "우수 사례"입니다. 낮은 빈도의 전략에 대해서는 이러한 관행을 권고합니다. 극도로 높은 빈도로 거래하는 경우, 더 나은 성능을 위해 시스템을 조정하는 대신 규칙 책을 무시해야합니다. 보다 밀접하게 결합 된 시스템이 바람직 할 수 있습니다.


알고리즘 거래 시스템의 구성 요소지도를 만드는 것은 그 자체만으로 가치가 있습니다. 그러나 최적의 접근 방식은 과거 및 실시간 시장 데이터 입력, 데이터 저장, 데이터 액세스 API, 백 테스터, 전략 매개 변수, 포트폴리오 구성, 위험 관리 및 자동화 된 실행 시스템을위한 별도의 구성 요소가 있는지 확인하는 것입니다.


예를 들어, 현재 사용중인 데이터 저장소가 상당한 수준의 최적화 작업을 수행하는 경우에도 성능이 저조한 경우 데이터 재사용 또는 데이터 액세스 API에 대한 최소한의 재 작성으로 스왑 아웃 될 수 있습니다. 백 테스터와 후속 구성 요소에 관한 한, 차이점은 없습니다.


분리 된 구성 요소의 또 다른 이점은 전체 시스템에서 다양한 프로그래밍 언어를 사용할 수 있다는 것입니다. 구성 요소의 통신 방법이 언어 독립적 인 경우 단일 언어로 제한 할 필요가 없습니다. 이것은 TCP / IP, ZeroMQ 또는 다른 언어 독립적 인 프로토콜을 통해 통신하는 경우에 해당됩니다.


구체적인 예를 들어, 팩토리 매니저와 실행 시스템은 SciPy와 IBPy를 사용하여 파이썬으로 작성되는 반면, 백 테스팅 시스템은 "숫자 처리"성능을 위해 C ++로 작성된 경우를 생각해보십시오.


성능 고려 사항.


실적은 대부분의 거래 전략에 중요한 고려 사항입니다. 고주파 전략의 경우 가장 중요한 요소입니다. "성능"은 알고리즘 실행 속도, 네트워크 대기 시간, 대역폭, 데이터 I / O, 동시성 / 병렬성 및 확장과 같은 광범위한 문제를 다룹니다. 이 영역들 각각은 커다란 교과서로 개별적으로 다루어 져 있으므로이 기사는 각 주제의 표면을 긁을뿐입니다. 아키텍처와 언어 선택은 이제 성능에 미치는 영향의 관점에서 논의 될 것입니다.


컴퓨터 과학의 아버지 중 한 명인 도널드 크 누스 (Donald Knuth)가 말한 지배적 인 지혜는 "조숙 한 최적화는 모든 악의 근원"이라는 것입니다. 이것은 거의 항상 그렇습니다 - 고주파수 거래 알고리즘을 구축 할 때를 제외하고! 저주파 전략에 관심이있는 사람들은 가능한 가장 간단한 방법으로 시스템을 구축하고 병목 현상이 나타나기 시작할 때만 최적화하는 것이 일반적인 방법입니다.


프로파일 링 도구는 병목 현상이 발생하는 위치를 확인하는 데 사용됩니다. MS Windows 또는 Linux 환경에서 위에 나열된 모든 요소에 대한 프로파일을 만들 수 있습니다. 타사 유틸리티뿐만 아니라이를 수행 할 수있는 운영 체제 및 언어 도구가 많이 있습니다. 언어 선택은 이제 성과의 맥락에서 논의 될 것입니다.


C ++, Java, Python, R 및 MatLab에는 모두 기본 데이터 구조 및 알고리즘 작업을위한 고성능 라이브러리가 표준 또는 외부 적으로 포함되어 있습니다. 파이썬에는 NumPy / SciPy가 포함되어 있지만 C ++에는 표준 템플릿 라이브러리가 들어 있습니다. 일반적인 수학적 작업은이 라이브러리에서 찾을 수 있으며 새로운 구현을 작성하는 것은 거의 도움이되지 않습니다.


한 가지 예외는 고도로 맞춤화 된 하드웨어 아키텍처가 필요하고 알고리즘이 독점적 인 확장 (예 : 사용자 정의 캐시)을 광범위하게 사용하는 경우입니다. 그러나 종종 "바퀴의 재발견"은 시간을 낭비하며 거래 인프라의 다른 부분을 개발하고 최적화하는 데 더 효과적 일 수 있습니다. 개발 시간은 독점 개발자와 관련하여 특히 귀중합니다.


연구 도구는 일반적으로 동일한 시스템에 위치하므로 지연은 실행 시스템의 문제입니다. 전자의 경우 대기 시간은 실행 경로의 여러 지점에서 발생할 수 있습니다. 데이터베이스는 (디스크 / 네트워크 대기 시간) 데이터베이스를 참조해야하며, 신호 (운영 시스템, 커널 메시징 대기 시간), 전송 된 거래 신호 (NIC 대기 시간) 및 처리 된 주문 (교환 시스템 내부 대기 시간)을 생성해야합니다.


높은 주파수 운용을 위해서는 네트워크 전송의 최적화뿐만 아니라 커널 최적화에 대해 잘 알고 있어야합니다. 이것은 심도있는 영역이며 기사의 범위를 크게 벗어나지 만 UHFT 알고리즘이 필요한 경우 필요한 지식의 깊이를 알고 있어야합니다!


캐싱은 양적 거래 개발자의 툴킷에서 매우 유용합니다. 캐싱은 자주 액세스되는 데이터를 성능이 뛰어난 액세스를 허용하는 방식으로 저장하는 개념으로 데이터의 잠재적 인 스 태니스를 희생합니다. 일반적으로 웹 개발에서는 디스크 기반 관계형 데이터베이스에서 데이터를 가져 와서 메모리에 저장하는 경우가 발생합니다. 이후의 데이터 요청은 "데이터베이스에 도달"할 필요가 없으므로 성능 향상이 중요 할 수 있습니다.


거래 상황에서 캐싱은 매우 유용 할 수 있습니다. 예를 들어, 전략 포트폴리오의 현재 상태는 리 밸런싱 될 때까지 캐시에 저장 될 수 있으므로 거래 알고리즘의 각 루프에서 목록을 재생성 할 필요가 없습니다. 이러한 재생성은 높은 CPU 또는 디스크 I / O 작업 일 수 있습니다.


그러나 캐싱은 자체적 인 문제가 아닙니다. 캐시 저장 장치의 휘발성으로 인해 캐시 데이터를 한꺼번에 재생성하면 인프라에 대한 상당한 수요가 발생할 수 있습니다. 또 다른 문제점은 개가 쌓여서 새 캐시 사본이 여러 번 생성되어 극도로 높은 부하가 발생하여 계단식 오류가 발생한다는 점입니다.


동적 메모리 할당은 소프트웨어 실행에 많은 비용이 듭니다. 따라서 고성능 트랜잭션 응용 프로그램이 프로그램 흐름 중에 메모리가 어떻게 할당되고 할당 해제되는지 잘 알고 있어야합니다. Java, C # 및 Python과 같은 최신 언어 표준은 모두 객체가 범위를 벗어날 때 동적으로 할당 된 메모리의 할당을 해제하는 자동 가비지 수집을 수행합니다.


가비지 수집은 오류를 줄이고 가독성을 높이기 때문에 개발 중에 매우 유용합니다. 그러나 특정 고주파 거래 전략에는 종종 차선책입니다. 이러한 경우 사용자 정의 가비지 수집이 종종 필요합니다. 예를 들어 Java에서 가비지 콜렉터와 힙 구성을 조정하면 HFT 전략에 대해 높은 성능을 얻을 수 있습니다.


C ++는 네이티브 가비지 콜렉터를 제공하지 않으므로 모든 메모리 할당 / 할당 해제를 객체 구현의 일부로 처리해야합니다. 잠재적으로 오류가 발생하기 쉽고 (잠재적으로 포인터가 매달 리지 만) 특정 응용 프로그램에서 힙에 오브젝트가 나타나는 방식을 세밀하게 제어하는 ​​것이 매우 유용합니다. 언어를 선택할 때 가비지 컬렉터가 작동하는 방식과 특정 유스 케이스에 최적화되도록 수정 될 수 있는지 여부를 반드시 확인하십시오.


알고리즘 거래 시스템의 많은 작업은 병렬 처리가 가능합니다. 이것은 복수의 프로그래밍 작업을 동시에 수행하는 개념, 즉 "병렬"을 의미합니다. 소위 "embarassingly parallel"알고리즘은 다른 단계와 완전히 독립적으로 계산 될 수있는 단계를 포함합니다. Monte Carlo 시뮬레이션과 같은 특정 통계 연산은 다른 무작위 추출 및 후속 경로 연산이 다른 경로에 대한 지식없이 계산 될 수 있기 때문에 당황스럽게 병렬 알고리즘의 좋은 예입니다.


다른 알고리즘은 부분적으로 병렬 처리 만 가능합니다. 유체 역학 시뮬레이션은 계산 영역이 다시 세분화 될 수있는 예이지만 궁극적으로 이러한 영역은 서로 통신해야하므로 작업이 부분적으로 순차적입니다. 병렬화 가능한 알고리즘은 Amdahl 's Law의 적용을받습니다. Amdahl의 법칙은 $ N $ 별도 프로세스 (예 : CPU 코어 또는 스레드)가 적용될 때 병렬 알고리즘의 성능 증가에 이론적 인 상한선을 제공합니다.


새로운 프로세서는 병렬 계산을 수행 할 많은 코어를 포함하므로 프로세서 클럭 속도가 정체 되었기 때문에 병렬화는 최적화 수단으로 점점 중요 해지고 있습니다. (비디오 게임을 주로하는) 소비자 그래픽 하드웨어의 등장으로 고도의 동시 작업을 위해 수 백 개의 "코어"가 포함 된 그래픽 처리 장치 (GPU)가 개발되었습니다. 이러한 GPU는 현재 매우 저렴합니다. Nvidia의 CUDA와 같은 상위 수준의 프레임 워크는 학계 및 금융 분야에서 널리 채택되었습니다.


이러한 GPU 하드웨어는 일반적으로 양적 금융의 연구 측면에만 적합하지만 다른보다 특수화 된 하드웨어 (FPGA를 포함하여 필드 프로그래밍 가능 게이트 어레이)는 (H) HFT에 사용됩니다. 요즘 대부분의 최신 langauges는 동시성 / 멀티 쓰레딩의 정도를 지원합니다. 따라서 모든 계산이 일반적으로 다른 것과 독립적이므로 백 테스터를 최적화하는 것이 간단합니다.


소프트웨어 엔지니어링 및 운영의 확장은 더 큰 요청, 더 높은 프로세서 사용 및 더 많은 메모리 할당과 같은 형태로 지속적으로로드를 처리 할 수있는 시스템의 기능을 의미합니다. 알고리즘 트레이딩에서는 더 많은 자본을 수용 할 수 있고 일관된 수익을 창출 할 수 있다면 전략을 확장 할 수 있습니다. 병목 현상없이 큰 거래량과 대기 시간을 견딜 수 있다면 거래 기술 스택이 확장됩니다.


시스템을 확장 할 수 있도록 설계해야하지만 병목 현상이 발생할 위치를 사전에 예측하기는 어렵습니다. 엄격한 로깅, 테스트, 프로파일 링 및 모니터링은 시스템의 확장을 크게 도와줍니다. 언어 그 자체는 종종 "unscalable"이라고 묘사됩니다. 이것은 일반적으로 어려운 사실이 아니라 오보의 결과입니다. 언어가 아닌 확장성에 대해 확인해야하는 총 기술 스택입니다. 확실히 특정 언어는 특정 사용 사례에서 다른 언어보다 성능이 뛰어나지 만 모든 언어에서 한 언어가 다른 언어보다 "더 나은"것은 아닙니다.


규모를 관리하는 한 가지 방법은 위에서 언급 한 것처럼 우려를 분리하는 것입니다. 시스템의 "스파이크 (spikes)"를 처리 할 수있는 기능 (예 : 갑작스러운 변동성)을 도입하기 위해 "메시지 대기열 아키텍처"를 만드는 것이 좋습니다. 이는 단순히 구성 요소간에 메시지 대기열 시스템을 배치하여 특정 구성 요소가 많은 요청을 처리 할 수없는 경우 주문이 "겹쳐서 표시"되도록하는 것을 의미합니다.


요청이 손실되는 대신 메시지가 처리 될 때까지 단순히 스택에 보관됩니다. 이는 특히 거래를 실행 엔진에 보내는 데 유용합니다. 엔진이 긴 대기 시간 동안 고통 받고 있다면 그것은 거래를 뒷받침 할 것입니다. 무역 신호 발생기와 실행 API 사이의 대기열은 잠재적 인 무역 미끄러짐을 희생하면서이 문제를 완화합니다. 존경받는 오픈 소스 메시지 큐 브로커는 RabbitMQ입니다.


하드웨어 및 운영 체제.


전략을 실행하는 하드웨어는 알고리즘의 수익성에 중요한 영향을 줄 수 있습니다. 고주파 거래자들에게만 국한된 문제는 아닙니다. 하드웨어 및 운영 체제의 부적절한 선택은 부적절한 순간에 컴퓨터 충돌 또는 재부팅으로 이어질 수 있습니다. 따라서 응용 프로그램의 위치를 ​​고려해야합니다. 일반적으로 개인 데스크톱 컴퓨터, 원격 서버, "클라우드"공급자 또는 교환기가 함께 배치 된 서버 사이에서 선택합니다.


데스크톱 컴퓨터는 특히 Windows 7/8, Mac OSX 및 Ubuntu와 같은 새로운 사용자 친화적 인 운영 체제에서 설치 및 관리가 간단합니다. 그러나 데스크톱 시스템에는 몇 가지 중요한 단점이 있습니다. 가장 중요한 점은 데스크톱 컴퓨터 용으로 설계된 운영 체제 버전은 재부팅 / 패치가 필요할 가능성이 높다는 것입니다 (종종 최악의 경우!). 또한 그래픽 사용자 인터페이스 (GUI)가 필요하기 때문에 계산 자원을 더 많이 사용합니다.


가정 (또는 지역 사무소) 환경에서 하드웨어를 사용하면 인터넷 연결 및 전원 가동 시간 문제가 발생할 수 있습니다. 데스크탑 시스템의 주요 이점은 원격 전용 서버 (또는 클라우드 기반 시스템)의 비슷한 속도의 일부분만으로도 상당한 연산 능력을 구입할 수 있다는 것입니다.


전용 서버 또는 클라우드 기반 시스템은 종종 데스크톱 옵션보다 비용이 비싸지 만 자동화 된 데이터 백업, 가동 시간 및 원격 모니터링을보다 직접적으로 보장 할 수있는 기능과 같은보다 중요한 중복 인프라를 허용합니다. 그들은 운영 체제의 원격 로그인 기능을 사용할 수 있어야하기 때문에 관리하기가 더 어렵습니다.


Windows에서는 일반적으로 GUI RDP (Remote Desktop Protocol)를 사용합니다. Unix 기반 시스템에서는 명령 줄 Secure SHell (SSH)이 사용됩니다. 유닉스 기반의 서버 인프라 스트럭처는 거의 항상 커맨드 라인 기반이며 GUI 기반 프로그래밍 도구 (예 : MatLab 또는 Excel)를 즉시 사용할 수 없게 만듭니다.


문구가 자본 시장에서 사용되는 공동 배치 서버는 단순히 거래 알고리즘의 대기 시간을 줄이기 위해 거래소 내에있는 전용 서버입니다. 이것은 알파를 생성하기 위해 낮은 대기 시간에 의존하는 특정 고주파수 거래 전략에 절대적으로 필요합니다.


하드웨어 선택과 프로그래밍 언어 선택의 마지막 측면은 플랫폼 독립적입니다. 여러 다른 운영 체제에서 코드를 실행해야합니까? 이 코드는 Intel x86 / x64와 같은 특정 유형의 프로세서 아키텍처에서 실행되도록 설계 되었습니까? 아니면 ARM에서 제조 한 것과 같은 RISC 프로세서에서 실행할 수 있습니까? 이러한 문제는 실행되는 전략의 빈도 및 유형에 크게 의존합니다.


탄력성과 테스트.


알고리즘 트레이딩에 많은 돈을 낭비하는 최선의 방법 중 하나는 탄력성이없는 시스템을 만드는 것입니다. 이는 중개 파산, 급격한 과도한 변동성, 클라우드 서버 제공 업체의 지역 차원의 중단 시간 또는 전체 거래 데이터베이스의 우발적 인 삭제와 같은 드문 경우가 발생할 경우 시스템의 내구성을 나타냅니다. 수년간의 이익은 잘 설계되지 않은 아키텍처로 단 몇 초 만에 제거 될 수 있습니다. 디버깅, 테스트, 로깅, 백업, 고 가용성 및 모니터링과 같은 문제를 시스템의 핵심 구성 요소로 고려하는 것이 절대적으로 중요합니다.


합리적으로 복잡한 양방향 거래 응용 프로그램의 경우 개발 시간의 50 % 이상이 디버깅, 테스트 및 유지 관리에 소요될 것입니다.


거의 모든 프로그래밍 언어는 관련 디버거와 함께 제공되거나 잘 알려진 타사 대안을 보유합니다. 본질적으로 디버거는 시스템의 상태를 조사하기 위해 일시적으로 실행을 중단시키는 코드 경로에 임의의 중단 점을 삽입하여 프로그램을 실행할 수있게합니다. 디버깅의 주요 이점은 알려진 충돌 지점 이전의 코드 동작을 조사하는 것이 가능하다는 것입니다.


디버깅은 프로그래밍 오류를 분석하기위한 도구 상자의 필수 구성 요소입니다. 그러나 Python과 같은 인터프리터 언어는 LOC가 적고 자세한 명령문이 적기 때문에 디버그하기가 더 쉽기 때문에 C ++ 또는 Java와 같은 컴파일 된 언어에서 더 널리 사용됩니다. 이러한 경향에도 불구하고 파이썬은 정교한 디버깅 도구 인 pdb를 제공합니다. Microsoft Visual C ++ IDE에는 광범위한 GUI 디버깅 유틸리티가 있으며, 명령 행 Linux C ++ 프로그래머의 경우 gdb 디버거가 있습니다.


소프트웨어 개발 테스트는 동작을 시뮬레이션하고 여러 코드 경로를 평가하여 시스템이 필요한대로 동작하는지 확인하기 위해 알려진 매개 변수와 결과를 코드베이스 내의 특정 기능, 메소드 및 객체에 적용하는 프로세스를 의미합니다. 보다 최근의 패러다임은 TDD (Test Driven Development)로 알려져 있습니다. TDD (Test Driven Development)에서는 구현되지 않은 특정 인터페이스에 대해 테스트 코드가 개발됩니다. 실제 코드베이스가 완료되기 전에 모든 테스트가 실패합니다. "빈 칸 채우기"라는 코드가 작성되면 결국 테스트가 끝나고 개발이 중단됩니다.


TDD는 성공적으로 수행하기 위해 광범위한 선행 사양 설계와 적절한 수준의 규율이 필요합니다. C ++에서 Boost는 단위 테스트 프레임 워크를 제공합니다. Java에서 JUnit 라이브러리는 동일한 목적을 달성하기 위해 존재합니다. 파이썬은 표준 라이브러리의 일부로서 unittest 모듈을 가지고있다. 다른 많은 언어는 단위 테스트 프레임 워크를 소유하고 있으며 여러 옵션이 있습니다.


프로덕션 환경에서는 정교한 로깅이 절대적으로 필요합니다. 로깅은 시스템의 실행 동작을 플랫 파일 또는 데이터베이스와 관련하여 다양한 정도의 심각도로 메시지를 출력하는 프로세스를 의미합니다. 로그는 예기치 않은 프로그램 런타임 동작을 검색 할 때 "공격의 첫 번째 줄"입니다. 불행히도 로깅 시스템의 단점은 사실 후에 발견되는 경향이 있습니다! 아래에 설명 된 백업과 마찬가지로 시스템이 설계되기 전에 로깅 시스템을 충분히 고려해야합니다.


Microsoft Windows와 Linux는 모두 광범위한 시스템 로깅 기능을 제공하며 프로그래밍 언어는 대부분의 사용 사례를 다루는 표준 로깅 라이브러리와 함께 제공되는 경향이 있습니다. 로깅 정보를 나중에 분석하기 위해서는 종종 로깅 정보를 중앙 집중화하는 것이 현명합니다. 성능이나 오류 감소에 대한 아이디어로 이어질 수 있기 때문에 거래 정보에 긍정적 인 영향을 줄 수 있습니다.


시스템 로깅이 과거에 있었던 일에 대한 정보를 제공하는 반면, 응용 프로그램을 모니터링하면 현재 일어나고있는 일에 대한 통찰력을 얻을 수 있습니다. 모니터링을 위해서는 시스템의 모든 측면을 고려해야합니다. 디스크 사용량, 사용 가능한 메모리, 네트워크 대역폭 및 CPU 사용량과 같은 시스템 수준 메트릭은 기본 부하 정보를 제공합니다.


비정상적인 가격 / 수량, 급격한 급감 및 다른 부문 / 시장에 대한 계정 노출과 같은 거래 메트릭스도 지속적으로 모니터링해야합니다. 또한 메트릭의 심각도에 따라 알림 메서드 (SMS, 자동 전화 통화)를 올리면 특정 메트릭이 위반되었을 때 알림을 제공하는 임계 값 시스템을 사용해야합니다.


시스템 모니터링은 종종 시스템 관리자 또는 운영 관리자의 도메인입니다. 그러나 독점적 인 거래 개발자로서 이러한 측정 기준은 더 큰 디자인의 일부로 설정되어야합니다. 모니터링을위한 많은 솔루션이 있습니다 : 특정 유스 케이스에 대한 메트릭을 광범위하게 사용자 정의 할 수있는 전용, 호스트 및 오픈 소스.


백업 및 고 가용성은 거래 시스템의 주된 관심사가되어야합니다. Consider the following two questions: 1) If an entire production database of market data and trading history was deleted (without backups) how would the research and execution algorithm be affected? 2) If the trading system suffers an outage for an extended period (with open positions) how would account equity and ongoing profitability be affected? The answers to both of these questions are often sobering!


It is imperative to put in place a system for backing up data and also for testing the restoration of such data. Many individuals do not test a restore strategy. If recovery from a crash has not been tested in a safe environment, what guarantees exist that restoration will be available at the worst possible moment?


Similarly, high availability needs to be "baked in from the start". Redundant infrastructure (even at additional expense) must always be considered, as the cost of downtime is likely to far outweigh the ongoing maintenance cost of such systems. I won't delve too deeply into this topic as it is a large area, but make sure it is one of the first considerations given to your trading system.


Choosing a Language.


Considerable detail has now been provided on the various factors that arise when developing a custom high-performance algorithmic trading system. The next stage is to discuss how programming languages are generally categorised.


Type Systems.


When choosing a language for a trading stack it is necessary to consider the type system . The languages which are of interest for algorithmic trading are either statically - or dynamically-typed . A statically-typed language performs checks of the types (e. g. integers, floats, custom classes etc) during the compilation process. Such languages include C++ and Java. A dynamically-typed language performs the majority of its type-checking at runtime. Such languages include Python, Perl and JavaScript.


For a highly numerical system such as an algorithmic trading engine, type-checking at compile time can be extremely beneficial, as it can eliminate many bugs that would otherwise lead to numerical errors. However, type-checking doesn't catch everything, and this is where exception handling comes in due to the necessity of having to handle unexpected operations. 'Dynamic' languages (i. e. those that are dynamically-typed) can often lead to run-time errors that would otherwise be caught with a compilation-time type-check. For this reason, the concept of TDD (see above) and unit testing arose which, when carried out correctly, often provides more safety than compile-time checking alone.


Another benefit of statically-typed languages is that the compiler is able to make many optimisations that are otherwise unavailable to the dynamically - typed language, simply because the type (and thus memory requirements) are known at compile-time. In fact, part of the inefficiency of many dynamically-typed languages stems from the fact that certain objects must be type-inspected at run-time and this carries a performance hit. Libraries for dynamic languages, such as NumPy/SciPy alleviate this issue due to enforcing a type within arrays.


Open Source or Proprietary?


One of the biggest choices available to an algorithmic trading developer is whether to use proprietary (commercial) or open source technologies. There are advantages and disadvantages to both approaches. It is necessary to consider how well a language is supported, the activity of the community surrounding a language, ease of installation and maintenance, quality of the documentation and any licensing/maintenance costs.


The Microsoft stack (including Visual C++, Visual C#) and MathWorks' MatLab are two of the larger proprietary choices for developing custom algorithmic trading software. Both tools have had significant "battle testing" in the financial space, with the former making up the predominant software stack for investment banking trading infrastructure and the latter being heavily used for quantitative trading research within investment funds.


Microsoft and MathWorks both provide extensive high quality documentation for their products. Further, the communities surrounding each tool are very large with active web forums for both. The software allows cohesive integration with multiple languages such as C++, C# and VB, as well as easy linkage to other Microsoft products such as the SQL Server database via LINQ. MatLab also has many plugins/libraries (some free, some commercial) for nearly any quantitative research domain.


There are also drawbacks. With either piece of software the costs are not insignificant for a lone trader (although Microsoft does provide entry-level version of Visual Studio for free). Microsoft tools "play well" with each other, but integrate less well with external code. Visual Studio must also be executed on Microsoft Windows, which is arguably far less performant than an equivalent Linux server which is optimally tuned.


MatLab also lacks a few key plugins such as a good wrapper around the Interactive Brokers API, one of the few brokers amenable to high-performance algorithmic trading. The main issue with proprietary products is the lack of availability of the source code. This means that if ultra performance is truly required, both of these tools will be far less attractive.


Open source tools have been industry grade for sometime. Much of the alternative asset space makes extensive use of open-source Linux, MySQL/PostgreSQL, Python, R, C++ and Java in high-performance production roles. However, they are far from restricted to this domain. Python and R, in particular, contain a wealth of extensive numerical libraries for performing nearly any type of data analysis imaginable, often at execution speeds comparable to compiled languages, with certain caveats.


The main benefit of using interpreted languages is the speed of development time. Python and R require far fewer lines of code (LOC) to achieve similar functionality, principally due to the extensive libraries. Further, they often allow interactive console based development, rapidly reducing the iterative development process.


Given that time as a developer is extremely valuable, and execution speed often less so (unless in the HFT space), it is worth giving extensive consideration to an open source technology stack. Python and R possess significant development communities and are extremely well supported, due to their popularity. Documentation is excellent and bugs (at least for core libraries) remain scarce.


Open source tools often suffer from a lack of a dedicated commercial support contract and run optimally on systems with less-forgiving user interfaces. A typical Linux server (such as Ubuntu) will often be fully command-line oriented. In addition, Python and R can be slow for certain execution tasks. There are mechanisms for integrating with C++ in order to improve execution speeds, but it requires some experience in multi-language programming.


While proprietary software is not immune from dependency/versioning issues it is far less common to have to deal with incorrect library versions in such environments. Open source operating systems such as Linux can be trickier to administer.


I will venture my personal opinion here and state that I build all of my trading tools with open source technologies. In particular I use: Ubuntu, MySQL, Python, C++ and R. The maturity, community size, ability to "dig deep" if problems occur and lower total cost ownership (TCO) far outweigh the simplicity of proprietary GUIs and easier installations. Having said that, Microsoft Visual Studio (especially for C++) is a fantastic Integrated Development Environment (IDE) which I would also highly recommend.


Batteries Included?


The header of this section refers to the "out of the box" capabilities of the language - what libraries does it contain and how good are they? This is where mature languages have an advantage over newer variants. C++, Java and Python all now possess extensive libraries for network programming, HTTP, operating system interaction, GUIs, regular expressions (regex), iteration and basic algorithms.


C++ is famed for its Standard Template Library (STL) which contains a wealth of high performance data structures and algorithms "for free". Python is known for being able to communicate with nearly any other type of system/protocol (especially the web), mostly through its own standard library. R has a wealth of statistical and econometric tools built in, while MatLab is extremely optimised for any numerical linear algebra code (which can be found in portfolio optimisation and derivatives pricing, for instance).


Outside of the standard libraries, C++ makes use of the Boost library, which fills in the "missing parts" of the standard library. In fact, many parts of Boost made it into the TR1 standard and subsequently are available in the C++11 spec, including native support for lambda expressions and concurrency.


Python has the high performance NumPy/SciPy/Pandas data analysis library combination, which has gained widespread acceptance for algorithmic trading research. Further, high-performance plugins exist for access to the main relational databases, such as MySQL++ (MySQL/C++), JDBC (Java/MatLab), MySQLdb (MySQL/Python) and psychopg2 (PostgreSQL/Python). Python can even communicate with R via the RPy plugin!


An often overlooked aspect of a trading system while in the initial research and design stage is the connectivity to a broker API. Most APIs natively support C++ and Java, but some also support C# and Python, either directly or with community-provided wrapper code to the C++ APIs. In particular, Interactive Brokers can be connected to via the IBPy plugin. If high-performance is required, brokerages will support the FIX protocol.


결론.


As is now evident, the choice of programming language(s) for an algorithmic trading system is not straightforward and requires deep thought. The main considerations are performance, ease of development, resiliency and testing, separation of concerns, familiarity, maintenance, source code availability, licensing costs and maturity of libraries.


The benefit of a separated architecture is that it allows languages to be "plugged in" for different aspects of a trading stack, as and when requirements change. A trading system is an evolving tool and it is likely that any language choices will evolve along with it.


양적 거래 시작하기?


QuantStart 목록을 구독해야하는 3 가지 이유 :


1. 퀀트 트레이딩 레슨.


계량 거래를 시작하는 데 도움이되는 힌트와 팁으로 가득한 무료 10 일간 코스에 즉시 액세스 할 수 있습니다!


2. 모든 최신 내용.


매주 나는 퀀트 스타트에서 모든 활동의 포장을 보내드릴 것입니다. 그래서 당신은 결코 다시 글을 놓치지 않을 것입니다.


현실감 넘치는 퀀 트레이딩 팁.


Dynamic Programming and Optimal Lookahead Strategies in High Frequency Trading with Transaction Costs.


25 Pages Posted: 3 Jan 2000.


Alexander Vigodner.


Bloomberg Financial Markets (BFM)


Date Written: October 1999.


An optimal stochastic discrete time control problem with non smooth penalty function is considered. This problem naturally arises in high-frequency trading on financial markets. The principle of dynamic programming is formulated for this problem. Existence and uniqueness of the optimal strategy is proved. An algorithm for building a suboptimal strategy is presented and approximating properties of this strategy are studied. In addition, a simplified strategy is described which is a solution of an isotonic regression problem. A class of problems is defined on which this strategy can replace the basic suboptimal strategy. The results are illustrated by examples.


JEL Classification: C2, C53, C61, F17, F47.


Alexander Vigodner (Contact Author)


Bloomberg Financial Markets (BFM) ( )


IBM-house 10th floor.


32 Weizmann Street.


종이 통계.


관련 전자 잡지.


자본 시장 : 시장 미세 구조 전자 저널.


이 주제에 대한 큐레이팅 된 기사를 보려면이 수수료 저널을 구독하십시오.


권장 논문.


빠른 링크.


약.


쿠키는이 사이트에서 사용됩니다. 거부하거나 더 자세히 알아 보려면 쿠키 페이지를 방문하십시오. This page was processed by apollo1 in 0.109 seconds.


Stochastic Optimal Control and Optimization of Trading Algorithms.


Although quant funds are quite common these days, for most people they’re still “black boxes” that do some “advanced math” or “machine learning” or even “artificial intelligence” inside. In one of our previous articles, we have shown our trading system (you can read it here: medium/tensorbox/the-trading-system-that-maximizes-our-edge-a64e95533959 ) In one of the future articles we may show how we build and test our predictive, or “alpha” models (which utilize advanced statistics and machine learning techniques). In this article, we’ll show you how we can optimize execution of trading algorithms and what kind of optimization tasks arise. There will be some advanced math, but we’ll try to keep it simple in the beginning and move to more advanced models.


Dynamic Programming Principle and the Hamilton-Jacobi-Bellman (HJB) equation.


Let’s assume we have a plane(or a rocket) flying from point A to point B, but as there’s lots of turbulence on the way, it can’t move in a straight line, as it’s constantly tossed in random directions. Control systems have to adjust trajectory (“control policy”) all the time, and since the amount of fuel is limited, it has to be done in an optimal way. The dynamic programming method breaks this decision problem into smaller subproblems. Richard Bellman’s principle of optimality describes how to do this:


An optimal policy has the property that whatever the initial state and initial decision are, the remaining decisions must constitute an optimal policy with regard to the state resulting from the first decision.


Basically, that means that part of the optimal trajectory is also an optimal trajectory: if the bold line between C and D wasn’t an optimal trajectory, we should’ve substituted it with some other (dashed) line. That is why such problems are usually solved backwards in time: if we’re at some (random) point C’ near C, we know how to get to C, and so on.


Mathematically, the problem could be formulated like this:


we need to minimize the value function:


over the time period [0,T], where C[ ] is the scalar cost rate function and D[ ] is a function that gives the economic value or utility at the final state, x ( t ) is the system state vector, x (0) is assumed given, and u( t ) for 0≤ t ≤ T is the control vector that we are trying to find.


For this simple system, the Hamilton–Jacobi–Bellman partial differential equation is:


subject to terminal condition:


In general, the goal of stochastic control problems is to maximize(minimize) some expected profit(cost) function by choosing an optimal strategy which itself affects the dynamics of the underlying stochastic system. Let’s have a look at some classic toy problems:


-The Merton Problem.


The agent is trying to maximize the expected utility of future wealth by trading a risky asset and a risk-free bank account. The agent’s actions affect her wealth, but at the same time, the random dynamics in traded asset modulate agent’s wealth in a stochastic manner. Or more strictly, agent is trying to maximize expectation of U(X), where X — agent’s wealth — is modeled as:


where W is a Brownian motion, used to model price of a risky asset:


where π is a self-financing trading strategy, μ is expected compounded rate of growth of the traded asset and r is compounded rate of return of the risk-free bank account.


-The Optimal Liquidation Problem.


Suppose that our alpha model signals us that it’s profitable to liquidate a large number N of coins at price St and we wish to do so by the end of the day at time T. Realistically, market does not have infinite liquidity, so it can’t absorb a large sell order at the best available price, which means we will walk the order book or even move the market and execute an order at a lower price (subject to market impact denoted as ‘h’ below). Hence, we should spread this out over time, and solve a stochastic control problem. We may also have a sense of urgency, represented by penalising utility function for holding non-zero invenotry throughout the strategy. Let νt denote the rate at which agent sells her coins at time t. Agent’s value function will look like:


where dQ=-νtdt — agent’s inventory, dS — coin price (as in Merton’s problem above), S’t=St-h(νt) — execution price and dX=νtS’tdt — agent’s cash.


-The Optimal Entry-Exit Problem for Statistical Arbitrage.


Suppose we have two co-integrated assets A and B (or, in trivial case, one asset on different exchanges) and have a long-short portfolio which is linear combination of these two assets. Optimal strategy should determine when to enter and exit such a portfolio and we can pose this problem as an optimal stopping problem. We can model the dynamics of the εt, co-integration factor of these assets, as.


where W is a standard Brownian motiom, κ is a rate of mean-reversion, θ is the level that the process mean-reverts to and σ is the volatility of the process. The agent’s performance, for example, for exiting the long position can be written as.


where c is the transaction cost for selling the portfolio, ρ represents urgency, usually given by the cost of margin trade and E[ ] denotes expectation conditional on εt= ε.


The value function will seek for the optimal stopping time when unwinding the position (long portfolio) maximizes the performance criteria. Alternatively, we can find performance criteria for entering long position, and finally, criteria for entering and exiting short positions.


There are, of course, many more optimal stochastic control problems in trading and almost any execution algorithm can be optimised using similar principles. Performance of two algorithms based on exact same signals may vary greatly, which is why it is not enough to have just a good “alpha” model that generates accurate predictions.


As a group of “quants” with academic background in Numerical Methods, Computational Mathematics, Game Theory and hands-on experience in High Frequency Trading and Machine Learning, our interest was in exploring opportunities in cryptocurrency markets, with the goal of exploiting various market inefficiencies to generate steady absolute returns (not correlated with market movements) with low volatility, or simply put, steady profit without major drawdowns. For more information please visit TensorBox and if you like what we do you can participate in our Initial Token Offering.


더 많이 또는 더 적은 박수를 치기 만하면 어떤 이야기가 실제로 돋보이는 지 우리에게 알릴 수 있습니다.


TensorBox.


As a group of “quants”, our interest is in exploring opportunities in cryptocurrency markets, with the goal of exploiting various market inefficiencies to generate steady absolute returns (not correlated with market movements) with low volatility.


QuantStart.


빠르게 성장하는 소매점 퀀텀 트레이더 커뮤니티를 지원하는 Quantcademy 개인 회원 포털에 가입하십시오. 당신은 당신의 가장 중요한 퀀트 트레이딩 질문에 대답 할 준비가되어있는 지식이 풍부하고 마음이 맞는 퀀트 트레이더 그룹을 찾을 수 있습니다.


퀀트 트레이딩에 관한 나의 eBook을 확인해보십시오. 여기서 저는 파이썬 툴로 수익성 높은 체계적인 트레이딩 전략을 만드는 법을 가르쳐드립니다.


Python 및 R을 사용하여 시계열 분석, 기계 학습 및 베이지안 통계를 사용하는 고급 거래 전략에 관한 새로운 전자 책을 살펴보십시오.


By Michael Halls-Moore on July 26th, 2013.


One of the most frequent questions I receive in the QS mailbag is "What is the best programming language for algorithmic trading?". The short answer is that there is no "best" language. Strategy parameters, performance, modularity, development, resiliency and cost must all be considered. This article will outline the necessary components of an algorithmic trading system architecture and how decisions regarding implementation affect the choice of language.


Firstly, the major components of an algorithmic trading system will be considered, such as the research tools, portfolio optimiser, risk manager and execution engine. Subsequently, different trading strategies will be examined and how they affect the design of the system. In particular the frequency of trading and the likely trading volume will both be discussed.


Once the trading strategy has been selected, it is necessary to architect the entire system. This includes choice of hardware, the operating system(s) and system resiliency against rare, potentially catastrophic events. While the architecture is being considered, due regard must be paid to performance - both to the research tools as well as the live execution environment.


What Is The Trading System Trying To Do?


Before deciding on the "best" language with which to write an automated trading system it is necessary to define the requirements. Is the system going to be purely execution based? Will the system require a risk management or portfolio construction module? Will the system require a high-performance backtester? For most strategies the trading system can be partitioned into two categories: Research and signal generation.


Research is concerned with evaluation of a strategy performance over historical data. The process of evaluating a trading strategy over prior market data is known as backtesting . The data size and algorithmic complexity will have a big impact on the computational intensity of the backtester. CPU speed and concurrency are often the limiting factors in optimising research execution speed.


Signal generation is concerned with generating a set of trading signals from an algorithm and sending such orders to the market, usually via a brokerage. For certain strategies a high level of performance is required. I/O issues such as network bandwidth and latency are often the limiting factor in optimising execution systems. Thus the choice of languages for each component of your entire system may be quite different.


Type, Frequency and Volume of Strategy.


The type of algorithmic strategy employed will have a substantial impact on the design of the system. It will be necessary to consider the markets being traded, the connectivity to external data vendors, the frequency and volume of the strategy, the trade-off between ease of development and performance optimisation, as well as any custom hardware, including co-located custom servers, GPUs or FPGAs that might be necessary.


The technology choices for a low-frequency US equities strategy will be vastly different from those of a high-frequency statistical arbitrage strategy trading on the futures market. Prior to the choice of language many data vendors must be evaluated that pertain to a the strategy at hand.


It will be necessary to consider connectivity to the vendor, structure of any APIs, timeliness of the data, storage requirements and resiliency in the face of a vendor going offline. It is also wise to possess rapid access to multiple vendors! Various instruments all have their own storage quirks, examples of which include multiple ticker symbols for equities and expiration dates for futures (not to mention any specific OTC data). This needs to be factored in to the platform design.


Frequency of strategy is likely to be one of the biggest drivers of how the technology stack will be defined. Strategies employing data more frequently than minutely or secondly bars require significant consideration with regards to performance.


A strategy exceeding secondly bars (i. e. tick data) leads to a performance driven design as the primary requirement. For high frequency strategies a substantial amount of market data will need to be stored and evaluated. Software such as HDF5 or kdb+ are commonly used for these roles.


In order to process the extensive volumes of data needed for HFT applications, an extensively optimised backtester and execution system must be used. C/C++ (possibly with some assembler) is likely to the strongest language candidate. Ultra-high frequency strategies will almost certainly require custom hardware such as FPGAs, exchange co-location and kernal/network interface tuning.


Research Systems.


Research systems typically involve a mixture of interactive development and automated scripting. The former often takes place within an IDE such as Visual Studio, MatLab or R Studio. The latter involves extensive numerical calculations over numerous parameters and data points. This leads to a language choice providing a straightforward environment to test code, but also provides sufficient performance to evaluate strategies over multiple parameter dimensions.


Typical IDEs in this space include Microsoft Visual C++/C#, which contains extensive debugging utilities, code completion capabilities (via "Intellisense") and straightforward overviews of the entire project stack (via the database ORM, LINQ); MatLab, which is designed for extensive numerical linear algebra and vectorised operations, but in an interactive console manner; R Studio, which wraps the R statistical language console in a fully-fledged IDE; Eclipse IDE for Linux Java and C++; and semi-proprietary IDEs such as Enthought Canopy for Python, which include data analysis libraries such as NumPy, SciPy, scikit-learn and pandas in a single interactive (console) environment.


For numerical backtesting, all of the above languages are suitable, although it is not necessary to utilise a GUI/IDE as the code will be executed "in the background". The prime consideration at this stage is that of execution speed. A compiled language (such as C++) is often useful if the backtesting parameter dimensions are large. Remember that it is necessary to be wary of such systems if that is the case!


Interpreted languages such as Python often make use of high-performance libraries such as NumPy/pandas for the backtesting step, in order to maintain a reasonable degree of competitiveness with compiled equivalents. Ultimately the language chosen for the backtesting will be determined by specific algorithmic needs as well as the range of libraries available in the language (more on that below). However, the language used for the backtester and research environments can be completely independent of those used in the portfolio construction, risk management and execution components, as will be seen.


Portfolio Construction and Risk Management.


The portfolio construction and risk management components are often overlooked by retail algorithmic traders. This is almost always a mistake. These tools provide the mechanism by which capital will be preserved. They not only attempt to alleviate the number of "risky" bets, but also minimise churn of the trades themselves, reducing transaction costs.


Sophisticated versions of these components can have a significant effect on the quality and consistentcy of profitability. It is straightforward to create a stable of strategies as the portfolio construction mechanism and risk manager can easily be modified to handle multiple systems. Thus they should be considered essential components at the outset of the design of an algorithmic trading system.


The job of the portfolio construction system is to take a set of desired trades and produce the set of actual trades that minimise churn, maintain exposures to various factors (such as sectors, asset classes, volatility etc) and optimise the allocation of capital to various strategies in a portfolio.


Portfolio construction often reduces to a linear algebra problem (such as a matrix factorisation) and hence performance is highly dependent upon the effectiveness of the numerical linear algebra implementation available. Common libraries include uBLAS, LAPACK and NAG for C++. MatLab also possesses extensively optimised matrix operations. Python utilises NumPy/SciPy for such computations. A frequently rebalanced portfolio will require a compiled (and well optimised!) matrix library to carry this step out, so as not to bottleneck the trading system.


Risk management is another extremely important part of an algorithmic trading system. Risk can come in many forms: Increased volatility (although this may be seen as desirable for certain strategies!), increased correlations between asset classes, counter-party default, server outages, "black swan" events and undetected bugs in the trading code, to name a few.


Risk management components try and anticipate the effects of excessive volatility and correlation between asset classes and their subsequent effect(s) on trading capital. Often this reduces to a set of statistical computations such as Monte Carlo "stress tests". This is very similar to the computational needs of a derivatives pricing engine and as such will be CPU-bound. These simulations are highly parallelisable (see below) and, to a certain degree, it is possible to "throw hardware at the problem".


Execution Systems.


The job of the execution system is to receive filtered trading signals from the portfolio construction and risk management components and send them on to a brokerage or other means of market access. For the majority of retail algorithmic trading strategies this involves an API or FIX connection to a brokerage such as Interactive Brokers. The primary considerations when deciding upon a language include quality of the API, language-wrapper availability for an API, execution frequency and the anticipated slippage.


The "quality" of the API refers to how well documented it is, what sort of performance it provides, whether it needs standalone software to be accessed or whether a gateway can be established in a headless fashion (i. e. no GUI). In the case of Interactive Brokers, the Trader WorkStation tool needs to be running in a GUI environment in order to access their API. I once had to install a Desktop Ubuntu edition onto an Amazon cloud server to access Interactive Brokers remotely, purely for this reason!


Most APIs will provide a C++ and/or Java interface. It is usually up to the community to develop language-specific wrappers for C#, Python, R, Excel and MatLab. Note that with every additional plugin utilised (especially API wrappers) there is scope for bugs to creep into the system. Always test plugins of this sort and ensure they are actively maintained. A worthwhile gauge is to see how many new updates to a codebase have been made in recent months.


Execution frequency is of the utmost importance in the execution algorithm. Note that hundreds of orders may be sent every minute and as such performance is critical. Slippage will be incurred through a badly-performing execution system and this will have a dramatic impact on profitability.


Statically-typed languages (see below) such as C++/Java are generally optimal for execution but there is a trade-off in development time, testing and ease of maintenance. Dynamically-typed languages, such as Python and Perl are now generally "fast enough". Always make sure the components are designed in a modular fashion (see below) so that they can be "swapped out" out as the system scales.


Architectural Planning and Development Process.


The components of a trading system, its frequency and volume requirements have been discussed above, but system infrastructure has yet to be covered. Those acting as a retail trader or working in a small fund will likely be "wearing many hats". It will be necessary to be covering the alpha model, risk management and execution parameters, and also the final implementation of the system. Before delving into specific languages the design of an optimal system architecture will be discussed.


Separation of Concerns.


One of the most important decisions that must be made at the outset is how to "separate the concerns" of a trading system. In software development, this essentially means how to break up the different aspects of the trading system into separate modular components.


By exposing interfaces at each of the components it is easy to swap out parts of the system for other versions that aid performance, reliability or maintenance, without modifying any external dependency code. This is the "best practice" for such systems. For strategies at lower frequencies such practices are advised. For ultra high frequency trading the rulebook might have to be ignored at the expense of tweaking the system for even more performance. A more tightly coupled system may be desirable.


Creating a component map of an algorithmic trading system is worth an article in itself. However, an optimal approach is to make sure there are separate components for the historical and real-time market data inputs, data storage, data access API, backtester, strategy parameters, portfolio construction, risk management and automated execution systems.


For instance, if the data store being used is currently underperforming, even at significant levels of optimisation, it can be swapped out with minimal rewrites to the data ingestion or data access API. As far the as the backtester and subsequent components are concerned, there is no difference.


Another benefit of separated components is that it allows a variety of programming languages to be used in the overall system. There is no need to be restricted to a single language if the communication method of the components is language independent. This will be the case if they are communicating via TCP/IP, ZeroMQ or some other language-independent protocol.


As a concrete example, consider the case of a backtesting system being written in C++ for "number crunching" performance, while the portfolio manager and execution systems are written in Python using SciPy and IBPy.


Performance Considerations.


Performance is a significant consideration for most trading strategies. For higher frequency strategies it is the most important factor. "Performance" covers a wide range of issues, such as algorithmic execution speed, network latency, bandwidth, data I/O, concurrency/parallelism and scaling. Each of these areas are individually covered by large textbooks, so this article will only scratch the surface of each topic. Architecture and language choice will now be discussed in terms of their effects on performance.


The prevailing wisdom as stated by Donald Knuth, one of the fathers of Computer Science, is that "premature optimisation is the root of all evil". This is almost always the case - except when building a high frequency trading algorithm! For those who are interested in lower frequency strategies, a common approach is to build a system in the simplest way possible and only optimise as bottlenecks begin to appear.


Profiling tools are used to determine where bottlenecks arise. Profiles can be made for all of the factors listed above, either in a MS Windows or Linux environment. There are many operating system and language tools available to do so, as well as third party utilities. Language choice will now be discussed in the context of performance.


C++, Java, Python, R and MatLab all contain high-performance libraries (either as part of their standard or externally) for basic data structure and algorithmic work. C++ ships with the Standard Template Library, while Python contains NumPy/SciPy. Common mathematical tasks are to be found in these libraries and it is rarely beneficial to write a new implementation.


One exception is if highly customised hardware architecture is required and an algorithm is making extensive use of proprietary extensions (such as custom caches). However, often "reinvention of the wheel" wastes time that could be better spent developing and optimising other parts of the trading infrastructure. Development time is extremely precious especially in the context of sole developers.


Latency is often an issue of the execution system as the research tools are usually situated on the same machine. For the former, latency can occur at multiple points along the execution path. Databases must be consulted (disk/network latency), signals must be generated (operating syste, kernal messaging latency), trade signals sent (NIC latency) and orders processed (exchange systems internal latency).


For higher frequency operations it is necessary to become intimately familiar with kernal optimisation as well as optimisation of network transmission. This is a deep area and is significantly beyond the scope of the article but if an UHFT algorithm is desired then be aware of the depth of knowledge required!


Caching is very useful in the toolkit of a quantitative trading developer. Caching refers to the concept of storing frequently accessed data in a manner which allows higher-performance access, at the expense of potential staleness of the data. A common use case occurs in web development when taking data from a disk-backed relational database and putting it into memory. Any subsequent requests for the data do not have to "hit the database" and so performance gains can be significant.


For trading situations caching can be extremely beneficial. For instance, the current state of a strategy portfolio can be stored in a cache until it is rebalanced, such that the list doesn't need to be regenerated upon each loop of the trading algorithm. Such regeneration is likely to be a high CPU or disk I/O operation.


However, caching is not without its own issues. Regeneration of cache data all at once, due to the volatilie nature of cache storage, can place significant demand on infrastructure. Another issue is dog-piling , where multiple generations of a new cache copy are carried out under extremely high load, which leads to cascade failure.


Dynamic memory allocation is an expensive operation in software execution. Thus it is imperative for higher performance trading applications to be well-aware how memory is being allocated and deallocated during program flow. Newer language standards such as Java, C# and Python all perform automatic garbage collection , which refers to deallocation of dynamically allocated memory when objects go out of scope .


Garbage collection is extremely useful during development as it reduces errors and aids readability. However, it is often sub-optimal for certain high frequency trading strategies. Custom garbage collection is often desired for these cases. In Java, for instance, by tuning the garbage collector and heap configuration, it is possible to obtain high performance for HFT strategies.


C++ doesn't provide a native garbage collector and so it is necessary to handle all memory allocation/deallocation as part of an object's implementation. While potentially error prone (potentially leading to dangling pointers) it is extremely useful to have fine-grained control of how objects appear on the heap for certain applications. When choosing a language make sure to study how the garbage collector works and whether it can be modified to optimise for a particular use case.


Many operations in algorithmic trading systems are amenable to parallelisation . This refers to the concept of carrying out multiple programmatic operations at the same time, i. e in "parallel". So-called "embarassingly parallel" algorithms include steps that can be computed fully independently of other steps. Certain statistical operations, such as Monte Carlo simulations, are a good example of embarassingly parallel algorithms as each random draw and subsequent path operation can be computed without knowledge of other paths.


Other algorithms are only partially parallelisable. Fluid dynamics simulations are such an example, where the domain of computation can be subdivided, but ultimately these domains must communicate with each other and thus the operations are partially sequential. Parallelisable algorithms are subject to Amdahl's Law, which provides a theoretical upper limit to the performance increase of a parallelised algorithm when subject to $N$ separate processes (e. g. on a CPU core or thread ).


Parallelisation has become increasingly important as a means of optimisation since processor clock-speeds have stagnated, as newer processors contain many cores with which to perform parallel calculations. The rise of consumer graphics hardware (predominently for video games) has lead to the development of Graphical Processing Units (GPUs), which contain hundreds of "cores" for highly concurrent operations. Such GPUs are now very affordable. High-level frameworks, such as Nvidia's CUDA have lead to widespread adoption in academia and finance.


Such GPU hardware is generally only suitable for the research aspect of quantitative finance, whereas other more specialised hardware (including Field-Programmable Gate Arrays - FPGAs) are used for (U)HFT. Nowadays, most modern langauges support a degree of concurrency/multithreading. Thus it is straightforward to optimise a backtester, since all calculations are generally independent of the others.


Scaling in software engineering and operations refers to the ability of the system to handle consistently increasing loads in the form of greater requests, higher processor usage and more memory allocation. In algorithmic trading a strategy is able to scale if it can accept larger quantities of capital and still produce consistent returns. The trading technology stack scales if it can endure larger trade volumes and increased latency, without bottlenecking .


While systems must be designed to scale, it is often hard to predict beforehand where a bottleneck will occur. Rigourous logging, testing, profiling and monitoring will aid greatly in allowing a system to scale. Languages themselves are often described as "unscalable". This is usually the result of misinformation, rather than hard fact. It is the total technology stack that should be ascertained for scalability, not the language. Clearly certain languages have greater performance than others in particular use cases, but one language is never "better" than another in every sense.


One means of managing scale is to separate concerns, as stated above. In order to further introduce the ability to handle "spikes" in the system (i. e. sudden volatility which triggers a raft of trades), it is useful to create a "message queuing architecture". This simply means placing a message queue system between components so that orders are "stacked up" if a certain component is unable to process many requests.


Rather than requests being lost they are simply kept in a stack until the message is handled. This is particularly useful for sending trades to an execution engine. If the engine is suffering under heavy latency then it will back up trades. A queue between the trade signal generator and the execution API will alleviate this issue at the expense of potential trade slippage. A well-respected open source message queue broker is RabbitMQ.


Hardware and Operating Systems.


The hardware running your strategy can have a significant impact on the profitability of your algorithm. This is not an issue restricted to high frequency traders either. A poor choice in hardware and operating system can lead to a machine crash or reboot at the most inopportune moment. Thus it is necessary to consider where your application will reside. The choice is generally between a personal desktop machine, a remote server, a "cloud" provider or an exchange co-located server.


Desktop machines are simple to install and administer, especially with newer user friendly operating systems such as Windows 7/8, Mac OSX and Ubuntu. Desktop systems do possess some significant drawbacks, however. The foremost is that the versions of operating systems designed for desktop machines are likely to require reboots/patching (and often at the worst of times!). They also use up more computational resources by the virtue of requiring a graphical user interface (GUI).


Utilising hardware in a home (or local office) environment can lead to internet connectivity and power uptime problems. The main benefit of a desktop system is that significant computational horsepower can be purchased for the fraction of the cost of a remote dedicated server (or cloud based system) of comparable speed.


A dedicated server or cloud-based machine, while often more expensive than a desktop option, allows for more significant redundancy infrastructure, such as automated data backups, the ability to more straightforwardly ensure uptime and remote monitoring. They are harder to administer since they require the ability to use remote login capabilities of the operating system.


In Windows this is generally via the GUI Remote Desktop Protocol (RDP). In Unix-based systems the command-line Secure SHell (SSH) is used. Unix-based server infrastructure is almost always command-line based which immediately renders GUI-based programming tools (such as MatLab or Excel) to be unusable.


A co-located server, as the phrase is used in the capital markets, is simply a dedicated server that resides within an exchange in order to reduce latency of the trading algorithm. This is absolutely necessary for certain high frequency trading strategies, which rely on low latency in order to generate alpha.


The final aspect to hardware choice and the choice of programming language is platform-independence. Is there a need for the code to run across multiple different operating systems? Is the code designed to be run on a particular type of processor architecture, such as the Intel x86/x64 or will it be possible to execute on RISC processors such as those manufactured by ARM? These issues will be highly dependent upon the frequency and type of strategy being implemented.


Resilience and Testing.


One of the best ways to lose a lot of money on algorithmic trading is to create a system with no resiliency . This refers to the durability of the sytem when subject to rare events, such as brokerage bankruptcies, sudden excess volatility, region-wide downtime for a cloud server provider or the accidental deletion of an entire trading database. Years of profits can be eliminated within seconds with a poorly-designed architecture. It is absolutely essential to consider issues such as debuggng, testing, logging, backups, high-availability and monitoring as core components of your system.


It is likely that in any reasonably complicated custom quantitative trading application at least 50% of development time will be spent on debugging, testing and maintenance.


Nearly all programming languages either ship with an associated debugger or possess well-respected third-party alternatives. In essence, a debugger allows execution of a program with insertion of arbitrary break points in the code path, which temporarily halt execution in order to investigate the state of the system. The main benefit of debugging is that it is possible to investigate the behaviour of code prior to a known crash point .


Debugging is an essential component in the toolbox for analysing programming errors. However, they are more widely used in compiled languages such as C++ or Java, as interpreted languages such as Python are often easier to debug due to fewer LOC and less verbose statements. Despite this tendency Python does ship with the pdb, which is a sophisticated debugging tool. The Microsoft Visual C++ IDE possesses extensive GUI debugging utilities, while for the command line Linux C++ programmer, the gdb debugger exists.


Testing in software development refers to the process of applying known parameters and results to specific functions, methods and objects within a codebase, in order to simulate behaviour and evaluate multiple code-paths, helping to ensure that a system behaves as it should. A more recent paradigm is known as Test Driven Development (TDD), where test code is developed against a specified interface with no implementation. Prior to the completion of the actual codebase all tests will fail. As code is written to "fill in the blanks", the tests will eventually all pass, at which point development should cease.


TDD requires extensive upfront specification design as well as a healthy degree of discipline in order to carry out successfully. In C++, Boost provides a unit testing framework. In Java, the JUnit library exists to fulfill the same purpose. Python also has the unittest module as part of the standard library. Many other languages possess unit testing frameworks and often there are multiple options.


In a production environment, sophisticated logging is absolutely essential. Logging refers to the process of outputting messages, with various degrees of severity, regarding execution behaviour of a system to a flat file or database. Logs are a "first line of attack" when hunting for unexpected program runtime behaviour. Unfortunately the shortcomings of a logging system tend only to be discovered after the fact! As with backups discussed below, a logging system should be given due consideration BEFORE a system is designed.


Both Microsoft Windows and Linux come with extensive system logging capability and programming languages tend to ship with standard logging libraries that cover most use cases. It is often wise to centralise logging information in order to analyse it at a later date, since it can often lead to ideas about improving performance or error reduction, which will almost certainly have a positive impact on your trading returns.


While logging of a system will provide information about what has transpired in the past, monitoring of an application will provide insight into what is happening right now . All aspects of the system should be considered for monitoring. System level metrics such as disk usage, available memory, network bandwidth and CPU usage provide basic load information.


Trading metrics such as abnormal prices/volume, sudden rapid drawdowns and account exposure for different sectors/markets should also be continuously monitored. Further, a threshold system should be instigated that provides notification when certain metrics are breached, elevating the notification method (, SMS, automated phone call) depending upon the severity of the metric.


System monitoring is often the domain of the system administrator or operations manager. However, as a sole trading developer, these metrics must be established as part of the larger design. Many solutions for monitoring exist: proprietary, hosted and open source, which allow extensive customisation of metrics for a particular use case.


Backups and high availability should be prime concerns of a trading system. Consider the following two questions: 1) If an entire production database of market data and trading history was deleted (without backups) how would the research and execution algorithm be affected? 2) If the trading system suffers an outage for an extended period (with open positions) how would account equity and ongoing profitability be affected? The answers to both of these questions are often sobering!


It is imperative to put in place a system for backing up data and also for testing the restoration of such data. Many individuals do not test a restore strategy. If recovery from a crash has not been tested in a safe environment, what guarantees exist that restoration will be available at the worst possible moment?


Similarly, high availability needs to be "baked in from the start". Redundant infrastructure (even at additional expense) must always be considered, as the cost of downtime is likely to far outweigh the ongoing maintenance cost of such systems. I won't delve too deeply into this topic as it is a large area, but make sure it is one of the first considerations given to your trading system.


Choosing a Language.


Considerable detail has now been provided on the various factors that arise when developing a custom high-performance algorithmic trading system. The next stage is to discuss how programming languages are generally categorised.


Type Systems.


When choosing a language for a trading stack it is necessary to consider the type system . The languages which are of interest for algorithmic trading are either statically - or dynamically-typed . A statically-typed language performs checks of the types (e. g. integers, floats, custom classes etc) during the compilation process. Such languages include C++ and Java. A dynamically-typed language performs the majority of its type-checking at runtime. Such languages include Python, Perl and JavaScript.


For a highly numerical system such as an algorithmic trading engine, type-checking at compile time can be extremely beneficial, as it can eliminate many bugs that would otherwise lead to numerical errors. However, type-checking doesn't catch everything, and this is where exception handling comes in due to the necessity of having to handle unexpected operations. 'Dynamic' languages (i. e. those that are dynamically-typed) can often lead to run-time errors that would otherwise be caught with a compilation-time type-check. For this reason, the concept of TDD (see above) and unit testing arose which, when carried out correctly, often provides more safety than compile-time checking alone.


Another benefit of statically-typed languages is that the compiler is able to make many optimisations that are otherwise unavailable to the dynamically - typed language, simply because the type (and thus memory requirements) are known at compile-time. In fact, part of the inefficiency of many dynamically-typed languages stems from the fact that certain objects must be type-inspected at run-time and this carries a performance hit. Libraries for dynamic languages, such as NumPy/SciPy alleviate this issue due to enforcing a type within arrays.


Open Source or Proprietary?


One of the biggest choices available to an algorithmic trading developer is whether to use proprietary (commercial) or open source technologies. There are advantages and disadvantages to both approaches. It is necessary to consider how well a language is supported, the activity of the community surrounding a language, ease of installation and maintenance, quality of the documentation and any licensing/maintenance costs.


The Microsoft stack (including Visual C++, Visual C#) and MathWorks' MatLab are two of the larger proprietary choices for developing custom algorithmic trading software. Both tools have had significant "battle testing" in the financial space, with the former making up the predominant software stack for investment banking trading infrastructure and the latter being heavily used for quantitative trading research within investment funds.


Microsoft and MathWorks both provide extensive high quality documentation for their products. Further, the communities surrounding each tool are very large with active web forums for both. The software allows cohesive integration with multiple languages such as C++, C# and VB, as well as easy linkage to other Microsoft products such as the SQL Server database via LINQ. MatLab also has many plugins/libraries (some free, some commercial) for nearly any quantitative research domain.


There are also drawbacks. With either piece of software the costs are not insignificant for a lone trader (although Microsoft does provide entry-level version of Visual Studio for free). Microsoft tools "play well" with each other, but integrate less well with external code. Visual Studio must also be executed on Microsoft Windows, which is arguably far less performant than an equivalent Linux server which is optimally tuned.


MatLab also lacks a few key plugins such as a good wrapper around the Interactive Brokers API, one of the few brokers amenable to high-performance algorithmic trading. The main issue with proprietary products is the lack of availability of the source code. This means that if ultra performance is truly required, both of these tools will be far less attractive.


Open source tools have been industry grade for sometime. Much of the alternative asset space makes extensive use of open-source Linux, MySQL/PostgreSQL, Python, R, C++ and Java in high-performance production roles. However, they are far from restricted to this domain. Python and R, in particular, contain a wealth of extensive numerical libraries for performing nearly any type of data analysis imaginable, often at execution speeds comparable to compiled languages, with certain caveats.


The main benefit of using interpreted languages is the speed of development time. Python and R require far fewer lines of code (LOC) to achieve similar functionality, principally due to the extensive libraries. Further, they often allow interactive console based development, rapidly reducing the iterative development process.


Given that time as a developer is extremely valuable, and execution speed often less so (unless in the HFT space), it is worth giving extensive consideration to an open source technology stack. Python and R possess significant development communities and are extremely well supported, due to their popularity. Documentation is excellent and bugs (at least for core libraries) remain scarce.


Open source tools often suffer from a lack of a dedicated commercial support contract and run optimally on systems with less-forgiving user interfaces. A typical Linux server (such as Ubuntu) will often be fully command-line oriented. In addition, Python and R can be slow for certain execution tasks. There are mechanisms for integrating with C++ in order to improve execution speeds, but it requires some experience in multi-language programming.


While proprietary software is not immune from dependency/versioning issues it is far less common to have to deal with incorrect library versions in such environments. Open source operating systems such as Linux can be trickier to administer.


I will venture my personal opinion here and state that I build all of my trading tools with open source technologies. In particular I use: Ubuntu, MySQL, Python, C++ and R. The maturity, community size, ability to "dig deep" if problems occur and lower total cost ownership (TCO) far outweigh the simplicity of proprietary GUIs and easier installations. Having said that, Microsoft Visual Studio (especially for C++) is a fantastic Integrated Development Environment (IDE) which I would also highly recommend.


Batteries Included?


The header of this section refers to the "out of the box" capabilities of the language - what libraries does it contain and how good are they? This is where mature languages have an advantage over newer variants. C++, Java and Python all now possess extensive libraries for network programming, HTTP, operating system interaction, GUIs, regular expressions (regex), iteration and basic algorithms.


C++ is famed for its Standard Template Library (STL) which contains a wealth of high performance data structures and algorithms "for free". Python is known for being able to communicate with nearly any other type of system/protocol (especially the web), mostly through its own standard library. R has a wealth of statistical and econometric tools built in, while MatLab is extremely optimised for any numerical linear algebra code (which can be found in portfolio optimisation and derivatives pricing, for instance).


Outside of the standard libraries, C++ makes use of the Boost library, which fills in the "missing parts" of the standard library. In fact, many parts of Boost made it into the TR1 standard and subsequently are available in the C++11 spec, including native support for lambda expressions and concurrency.


Python has the high performance NumPy/SciPy/Pandas data analysis library combination, which has gained widespread acceptance for algorithmic trading research. Further, high-performance plugins exist for access to the main relational databases, such as MySQL++ (MySQL/C++), JDBC (Java/MatLab), MySQLdb (MySQL/Python) and psychopg2 (PostgreSQL/Python). Python can even communicate with R via the RPy plugin!


An often overlooked aspect of a trading system while in the initial research and design stage is the connectivity to a broker API. Most APIs natively support C++ and Java, but some also support C# and Python, either directly or with community-provided wrapper code to the C++ APIs. In particular, Interactive Brokers can be connected to via the IBPy plugin. If high-performance is required, brokerages will support the FIX protocol.


결론.


As is now evident, the choice of programming language(s) for an algorithmic trading system is not straightforward and requires deep thought. The main considerations are performance, ease of development, resiliency and testing, separation of concerns, familiarity, maintenance, source code availability, licensing costs and maturity of libraries.


The benefit of a separated architecture is that it allows languages to be "plugged in" for different aspects of a trading stack, as and when requirements change. A trading system is an evolving tool and it is likely that any language choices will evolve along with it.


양적 거래 시작하기?


QuantStart 목록을 구독해야하는 3 가지 이유 :


1. 퀀트 트레이딩 레슨.


계량 거래를 시작하는 데 도움이되는 힌트와 팁으로 가득한 무료 10 일간 코스에 즉시 액세스 할 수 있습니다!


2. 모든 최신 내용.


매주 나는 퀀트 스타트에서 모든 활동의 포장을 보내드릴 것입니다. 그래서 당신은 결코 다시 글을 놓치지 않을 것입니다.


현실감 넘치는 퀀 트레이딩 팁.

Comments