Wednesday 7 March 2018

알고리즘 거래 시스템을위한 최상의 프로그래밍 언어


알고리즘 트레이딩 시스템을위한 최상의 프로그래밍 언어
App Store를 통해 가져 오기 우리의 응용 프로그램 에서이 게시물을 읽으십시오!
양적 금융 프로그래밍 언어.
2 주 이후로 나는 퀀텀 파이낸스에 대한 연구를 시작했습니다. 이 시간 동안, 나는 많은 것들을 발견 할 수 있었고 그걸 가지고 많은 의문이 떠올랐다. 많은 뉴스 또는 경제 저널 / 잡지는 HFT / 알고리즘 트레이딩에 대해 글을 씁니다. 그들 대부분은 회사 나 소프트웨어 개발자가 C ++을 선호한다고 말한다. 일부 기사에서 작가는 Java, C #, C 또는 ASM에 대해서도 이야기합니다. C ++에 대한 이유를 찾으려고 노력했지만 성공하지 못했습니다. 이 항목에서는 필자가 필요로하는 답변을 제공하지 않습니다 (왜 C ++이 여전히 양적 금융 분야에서 널리 사용되는 언어입니까?)
여기에 내 질문이 있습니다 : 1. 왜 C ++? 일부 회사에서는 ASM을 사용할 수도 있습니다 (밀리 초가 중요한 역할을하는 HFT에서는 ASM을 상상할 수 있습니다). 그러나 중간 주파수 거래 나 알고리즘에서? 속도 때문인가요? C ++ 용 퀀텀 파이낸셜 라이브러리를 찾았지만 많이 찾을 수 없었습니다. 유일한 것은 QuantLib, MatLib 및 TA-Lib입니다. 그러나 차트 API / Libs 또는 자습서는 없습니다. 튜토리얼을 아무도하지 않는 것 같습니다. 2. 왜 일부 사람들은 자바를 선택합니까? Java는 매우 대중적인 언어이며 많은 API / Libs를 보유하고 있으며 커뮤니티가 커지고 있음을 알고 있습니다. 그러나 속도가 중요한 역할을 할 수 있다면 Java가 가장 빠를 수는 없습니다 (가상 환경 때문에). 아니면 내가 틀렸어? 3. 왜 중기 거래 나 고문 거래를 위해 파이썬을 사용하지 않는가? Python에는 MatLib, TA-Lib, Pyqtgraph와 같은 많은 Apis / Lib이 있습니다. 좋아요, 파이썬이 가장 빠르지는 않습니다. 4.이 토론에서 C ++은 여전히 ​​양적 금융에서 매우 대중적인 언어입니까? 어떤 사람들은 C #이 퀀텀 파이낸스 개발에 훨씬 더 좋을 것이라고 주장합니다. 정말 사실입니까? Libs, APIs, Tutorials 등은 어떻습니까?
그리고 나의 마지막 질문, 퀀텀 파이낸싱을위한 언어를 선택하기위한 중요한 자산은 무엇입니까? ASM은 언어가 가장 빠르며 빠르게 계산해야하는 매우 복잡한 계산에 사용되기 때문에 ASM에 대해 말하지 않습니다. 그러나 C ++, C #, Python 및 Java는 무엇입니까? 저에게는 Libs와 Tutorials / Examples가 있어야한다는 점이 중요합니다. 그리고 처음에는 파이썬으로 시작했지만 읽은 후에는 더 이상 파이썬에 대해 확신 할 수 없습니다.
사람들은 이러한 언어의 실용적인 사용보다는 항상 이러한 언어의 이론적 인 이점에 대해 토론하기 때문에 결국이 문제를 잘못 이해하게됩니다.
Haskell은 우아하고 많은 이론적 이점 (언어 간결함, 직교성, 매개 변수 다형성, ADT, 고차 함수, 스마트 컴파일러)을 가지고 있으며 25 년 동안 계속되었지만 여전히 금융 분야의 주류는 아닙니다.
파이썬은 추한 언어입니다. 신택스는 표현력이 뛰어나지 만 GIL, 동적 타이핑, 객체 지향 패러다임 등과 같은 디자인 결정은 본질적으로 반 평행이며 각 프로세서에 수백 개의 코어가있을 때 수십 년이 지나면 우리 아이들은 그런 언어 (플로피 디스크와 같은 다른 것들)의 불명료 함과 obsoleteness를 웃어 라.
그러나 오늘날 거의 모든 사람들이 파이썬을 선택하도록 권장합니다. 왜?
언어 (또는 그와 관련된 모든 기술)의 미래는 커뮤니티, 도서관 및 개발 도구의 풍부함, 해당 언어로 된 레거시 코드의 자체 영속성에 의해 결정되며 결코 이론적 인 이점이 없습니다. 우리는 우리가 자바를 어떻게 싫어하는지 에세이를 쓸 수 있습니다. ROOT 및 Boost 라이브러리; XML의 장황함. 그러나 이러한 것들은 제작 강도 도구 나 라이브러리를 기꺼이 만들려는 사용자를 대량으로 확보했기 때문에 여기에 있습니다. F #과 같은 수십 가지 기능 언어가 올거예요. 하지만 C ++의 레거시 코드 때문에 엄청난 양의 C ++이 남아있을 것입니다. 게다가 C ++ 11은 개발 경로에서 이론적 인 사고를 분류하는 데있어 막대한 이정표가됩니다.
내가 조심스럽게 접근 할 몇 가지 선택 :
동시 및 기능적 패러다임을 중심으로 구축 된 언어 : Scala, F #. Dropbox, Lime, Tower Research, Credit Suisse 등에서 프로덕션에 사용되기 때문에 조심스럽게 접근해야한다고 말하고 싶지만 이러한 언어는 주류 사용으로 상승하는 데 더 많은 시간이 걸렸습니다. 프로세서 아키텍처에서. 지금이 언어로 귀하의 시간을 투자하는 것이 지금으로부터 5 년 후에 정확히 이루어질 지 여부를 알려주는 것이 어렵지만, 우리 모두는 이러한 언어가 궁극적으로 동의 할 것 같습니다. 도메인 특정 언어 : Julia. 불행하게도, Julia는 "C-speed 수치 내부 루프"로 시장을 내고 있습니다. 이 줄리아 사용자들과 논쟁 할 파이썬 군중들의 동일한 하위 집합을 끌어 당깁니다. 이들은 항상 Cython으로 떨어질 수 있기 때문에 관련이 없습니다. 두 군중 모두 운명의 패러다임을 옹호하고 저품질 개발자를 끌어 들이고 있습니다. (필자는 불행히도 Julia에는 유형 매개 변수 다중 메소드, 대칭 코 루틴, 외국어와의 깔끔한 인터페이스, Lisp 영향 및 메타 프로그래밍 지원 등 사람들이 모르는 많은 것들이 있기 때문에)
그것으로 몇 가지 선택을 권장합니다.
큰 형제를 지원하는 언어 : Go, Swift, C #. Google의 지원 외에도 Go는 중국에서 매우 인기가 있습니다. 마이크로 소프트는 C #을 오픈 소스 화하여 엄청난 발전을 이루었습니다. 많은 양질의 UI 개발 도구가 항상 Apple의 핵심 언어를 중심으로 만들어집니다. C / C ++을 시스템 레벨 프로그래밍 언어로 대체하려는 언어 : D, Nimrod. D는 이미 페이스 북의 지원을 받고 있으며, Nimrod는 Python 구문의 표현력을 유지하면서 인상적인 벤치 마크를 달성하고 특정 시스템 수준의 프로그래밍 프로젝트에 사용됩니다. 그러나 두 가지 방법 모두 여전히 메모리 관리에 대한 GC 접근법에 의존한다는 점에 유의하십시오.
위의 것들 중 어느 하나가 훌륭한 개발자를 대량으로 얻었습니까? 나는 그렇게 생각하지 않는다. 당신을위한 진정한 해결책은 프로그래밍 언어가 실제로 받아들이 기가 어렵지 않다는 것입니다! 더 중요한 것은 특정 언어보다는 프로그램을 디자인하는 방법을 선택하는 것입니다. 6 가지 주요 언어 패러다임으로 시간을 보냅니다.
(Lisp, ML, F #) 선언적 명세 (C ++ 템플릿, 하스켈, 프롤로그) 구문 추상화 (Lisp) 병렬 처리 (Cilk, SISAL, Clojure, Erlang) Coroutines (C #, F #, 하스켈, 스키마, 아이콘)
양적 거래는 종종 다음 세 가지 핵심 분야에서 개념을 불러옵니다.
알고리즘, 디자인 패턴 및 데이터 구조 : B - 트리, 건너 뛰기 목록, 메모 작성, DP 등 시스템 프로그래밍 : 메모리 주소 지정, 어셈블리, 링크, 힙 / 스택, 캐시 등 데이터베이스 : 정규화, 2 단계 커밋, 복제, 미러링, 스키마 디자인 등
그리고 스펙트럼의 퀀트 개발자가 더 가까이 다가 가면 :
불행히도이 질문에 대한 정답은 없습니다. 주말에 운전해야하는 자동차와 같습니다.
C ++은 양적 금융 분야에서 널리 사용되는 언어이지만 대개 파생 상품 가격과 같이 애플리케이션 백본을 구축하는 데만 사용됩니다 (항상 그렇지는 않음). 왜 C ++인가? C ++은 플랫폼 독립적 인 것이기 때문에 좋은 선택입니다. Linux, Mac, Windows 등의 옵션 가격 코드를 기본적으로 만들 수 있습니다. QuantLib이 좋은 예입니다.
C #은 금융 분야에서 또 다른 인기있는 언어입니다. 우리는 C #을 사용하여 거래 응용 프로그램을 만들고 다른 은행에서 XML 데이터를 파싱하고 웹 서버를 만드는 등의 작업을 수행 할 수 있습니다. 물론 C #에서 파생 가격을 설정할 수도 있지만 성능을 최적화 할 수는 없습니다. C ++에서는 OpenMP로 워크로드를 분할하고 Monte-Carlo 루프 등을 벡터화하는 등 C #으로 처리하기가 더 어려워졌습니다.
C #은 양적 금융에서 C ++보다 나은 언어는 아닙니다. 그것은 정말로 당신이하고 싶은 것에 달려 있습니다. 예를 들어 아무도 HPC 거래에 C #을 사용하지 않습니다.
양적 금융 분야의 모든 사람들이 하드 코어 프로그래밍을 할 수있는 것은 아니지만 대부분은 그렇지 않습니다. Python (Excel VBL 또는 R)이 더 좋은 언어입니다.
첫 번째 직업에 대해 배우고 싶다면 C ++부터 시작하십시오. QuantLib에 대해 이해하십시오.

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 사이의 대기열은 잠재적 인 무역 미끄러짐을 희생하면서이 문제를 완화합니다. 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. 두 방법 모두 장단점이 있습니다. 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. 모든 최신 내용.
매주 나는 퀀트 스타트에서 모든 활동의 포장을 보내드릴 것입니다. 그래서 당신은 결코 다시 글을 놓치지 않을 것입니다.
현실감 넘치는 퀀 트레이딩 팁.

Best programming language for algorithmic trading systems.
But still no makeup Herbalife again nowhere to go.
In this post, there is no logic.
흠. kum raz nudeu temu dumala, takoj post shikarnuej, spasibo!
Even if you don’t succeed in having normal erection you should not stop trying! Just don’t give up!
You are not the only person that suffers from you erectile dysfunction. Your wife is affected too.
Very amusing opinion.
Older men have the highest suicide rate in the world due to problems with masculine health.
Impotence ruins more families than adultery! Isn’t it a reason to take care of your sexual health?
Best Programming Language for Algorithmic Trading Systems?
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 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".
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 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.
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. 두 방법 모두 장단점이 있습니다. 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.
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.
Mike is the founder of QuantStart and has been involved in the quantitative finance industry for the last five years, primarily as a quant developer and later as a quant trader consulting for hedge funds.

올바른 알고리즘 거래 소프트웨어 따기.
알고리즘 트레이딩을 사용하는 동안 거래자는 힘들게 벌어 들인 돈을 자신이 사용하는 거래 소프트웨어로 신뢰합니다. 컴퓨터 소프트웨어의 올바른 부분은 거래 주문을 효과적이고 정확하게 수행하는 데 매우 중요합니다. 결함이있는 소프트웨어 또는 필요한 기능이없는 소프트웨어는 막대한 손실을 초래할 수 있습니다. 이 기사에서는 알고리즘 거래에 적합한 소프트웨어를 선택하는 데 고려해야 할 주요 사항을 살펴 봅니다. (자세한 내용은 : 알고리즘 트레이딩의 기초 : 개념과 예제를 참조하십시오.)
[알고리즘 트레이딩 소프트웨어는 기술적 인 분석에 대한 깊은 이해를 필요로합니다. 결국 기술 지표는 종종 이러한 거래 시스템의 입력으로 사용됩니다. Investopedia의 Technical Analysis Course에서는 가격 행동을 주도하는 기술적 패턴, 추세, 신호 및 지표를 식별하는 방법에 대한 심층적 인 개요를 제공합니다. 5 시간이 넘는 주문형 비디오, 연습 및 양방향 컨텐츠로 모든 주요 기술 분석 형식과 사용 사례를 보여주는 사례 연구를 배우게됩니다.]
알고리즘 거래에 대한 빠른 입문서.
알고리즘은 특정 작업을 완료하기위한 구체적인 단계별 지침 집합으로 정의됩니다. Pac-Man과 같은 중독성이 강한 컴퓨터 게임이나 엄청난 수의 기능을 제공하는 스프레드 시트 일 수 있습니다. 각 프로그램은 기본 알고리즘을 기반으로하는 특정 지침 세트를 따릅니다.
알고리즘 트레이딩은 거래 주문을하기 위해 정의 된 명령어 세트를 따르는 컴퓨터 프로그램을 사용하는 프로세스입니다. 알고리즘 거래 프로그램의 목적은 수익성있는 기회를 동적으로 식별하고 거래를 배치하여 인간 상인이 일치시킬 수없는 속도와 빈도로 수익을 창출하는 것입니다. 더 높은 정확도와 빠른 실행 속도의 이점을 감안할 때 컴퓨터 알고리즘을 기반으로 한 거래 활동은 엄청난 인기를 얻고 있습니다. (더 많은 것을 위해, 보십시오 : 자동 무역 시스템의 찬부 양론.)
누가 알고리즘 트레이딩 소프트웨어를 사용합니까?
알고리즘 거래는 헤지 펀드, 투자 은행 및 독점 거래 회사와 같은 대형 거래 회사가 지배합니다. 규모가 크기 때문에 풍부한 자원을 이용할 수 있으므로 대개 전용 데이터 센터 및 지원 직원이있는 대규모 거래 시스템을 비롯하여 독점적 인 거래 소프트웨어를 구축합니다.
개인 수준에서 경험이 풍부한 독점 상인 및 퀀트는 알고리즘 거래를 사용합니다. 기술에 익숙하지 않은 독점 상인은 알고리즘 거래 수요를 위해 미리 준비된 거래 소프트웨어를 구매할 수 있습니다. 이 소프트웨어는 브로커에서 제공하거나 제 3 자 제공 업체에서 구입할 수 있습니다. 콴트는 거래 및 컴퓨터 프로그래밍에 대한 지식이 뛰어나며 거래 소프트웨어를 독자적으로 개발합니다. (더 많은 것을 위해, 보십시오 : 퀀트 : 그들이하는 일 및 그들이 진화 한 방식.)
알고리즘 트레이딩 소프트웨어 - 빌드 또는 구매?
알고리즘 거래 소프트웨어에 액세스하는 방법에는 빌드 또는 구매 두 가지가 있습니다.
기성품 소프트웨어를 구입하면 신속하고 신속하게 액세스 할 수 있으며, 직접 구축하면 원하는대로 사용자 정의 할 수 있습니다. The automated trading software is often costly to purchase and it may be full of loopholes, which, if ignored, may lead you to losses. 높은 비용으로 인해 알고리즘 거래 벤처에서 현실적인 수익 잠재력이 사라질 수 있습니다. 반면에 알고리즘 거래 소프트웨어를 직접 만들려면 시간과 노력 그리고 깊은 지식이 필요하며 아직까지는 완벽하지 않을 수 있습니다.
The risk involved in automatic trading is very high, which can lead to large losses. 구매 또는 빌드를 결정하는 경우에도 필요한 기본적인 기능에 익숙해 져야합니다.
알고리즘 트레이딩 소프트웨어의 주요 특징.
시장 및 회사 데이터의 가용성 : 모든 거래 알고리즘은 실시간 시장 데이터 및 가격 견적에 따라 작동하도록 설계되었습니다. 몇 가지 프로그램은 EPS 및 PE 비율과 같은 회사 기본 데이터를 설명하기 위해 사용자 정의됩니다. 모든 알고리즘 거래 소프트웨어에는 실시간 시장 데이터 피드와 회사 데이터 피드가 있어야합니다. 시스템에 내장되어 있어야하며 대체 소스에서 쉽게 통합 할 수있는 조항이 있어야합니다. 다양한 시장에 대한 연결성 : 여러 시장에서 일하기를 원하는 거래자는 각 거래소가 TCP / IP, 멀티 캐스트 또는 FIX와 같은 다른 형식으로 데이터 피드를 제공 할 수 있습니다. 소프트웨어가 다른 형식의 피드를 받아 들일 수 있어야합니다. 또 다른 옵션은 블룸버그 (Bloomberg)와 로이터 (Reuters)와 같은 제 3 자 데이터 공급 업체와 거래하는 것인데, 이는 서로 다른 거래소의 시장 데이터를 집계하여 최종 고객에게 통일 된 형식으로 제공합니다. 알고리즘 거래 소프트웨어는 필요에 따라 이러한 통합 피드를 처리 할 수 ​​있어야합니다. 대기 시간 :이 목록의 가장 작은 단어는 알 고잉 거래에있어 가장 중요한 요소입니다. 대기 시간은 한 응용 프로그램에서 다른 응용 프로그램으로 데이터 포인트를 이동시키는 데 소요되는 시간 지연입니다. 다음과 같은 일련의 이벤트를 고려하십시오. 교환기에서 소프트웨어 공급 업체의 데이터 센터 (DC)로 가격 견적을 받으려면 0.2 초, 거래 화면에 도달하려면 데이터 센터에서 0.3 초, 수신 된 견적을 처리하는 거래 소프트웨어는 0.1 초, 그것은 거래를 분석하고 배치하는데, 거래 주문 0.2 초는 중개인에게, 0.3 초는 중개인이 주문을 교환기로 전달하도록합니다.
총 경과 시간 = 0.2 + 0.3 + 0.1 + 0.3 + 0.2 + 0.3 = 총 1.4 초.
오늘날의 역동적 인 거래 환경에서 최초의 가격 견적은이 1.4 초 내에 여러 번 변경되었을 것입니다. 이 지연은 알고리즘 거래 벤처를 만들거나 깰 수 있습니다. 시간 지연없이 가장 최신의 정확한 정보를 얻으려면이 대기 시간을 가능한 최저 수준으로 유지해야합니다.
대기 시간은 마이크로 초로 단축되었으며 거래 시스템에서 가능한 한 낮게 유지하려는 모든 시도가 이루어져야합니다. 몇 가지 조치로는 교환기에 직접 연결하여 중간에 공급 업체를 제거하여 데이터를 빠르게 가져 오는 것, 분석 알고리즘과 의사 결정을 위해 0.1 + 0.3 = 0.4 초 미만이 소요되도록 거래 알고리즘을 개선하십시오. 또는 중개인을 제거하고 0.2 초를 절약하기 위해 거래소로 거래를 직접 보냄으로써 가능합니다.
구성 가능성 및 사용자 정의 : 대부분의 알고리즘 거래 소프트웨어는 200 일 MA와 50 일 이동 평균 (MA)의 교차를 기반으로하는 표준 내장 거래 알고리즘을 제공합니다. 상인은 100 일 간의 MA를 통해 20 일 MA로 전환하여 실험을 원할 수 있습니다. 소프트웨어가 매개 변수의 이러한 사용자 정의를 제공하지 않는 한, 상인은 내장 된 고정 기능에 의해 제한 될 수 있습니다. 구매 또는 구축 여부에 관계없이 거래 소프트웨어에는 높은 수준의 사용자 정의 및 구성 가능성이 있어야합니다. 사용자 정의 프로그램 작성 기능 : Matlab, Python, C ++, JAVA 및 Perl은 거래 소프트웨어를 작성하는 데 사용되는 일반적인 프로그래밍 언어입니다. 타사 공급 업체에서 판매하는 대부분의 거래 소프트웨어는 사용자 정의 프로그램을 작성할 수있는 기능을 제공합니다. 이를 통해 상인은 자신이 개발 한 모든 거래 개념을 실험하고 시도 할 수 있습니다. 원하는 프로그래밍 언어로 코딩을 제공하는 소프트웨어가 선호됩니다. (자세한 내용은 무역 시스템 코딩 : 소개를 참조하십시오.) 이력 데이터의 백 테스팅 기능 : 백 테스팅 시뮬레이션은 과거 데이터에 대한 거래 전략 테스트를 포함합니다. 성공 (또는 실패 또는 필요한 변경)을 증명하는 과거 데이터의 전략의 실용성과 수익성을 평가합니다. 이 필수 기능에는 백 테스팅을 수행 할 수있는 기록 데이터의 가용성도 수반되어야합니다. 거래 인터페이스와의 통합 : 알고리즘 거래 소프트웨어는 원하는 기준의 발생에 따라 거래를 자동으로 처리합니다. 소프트웨어는 거래를 수행하기 위해 브로커 네트워크에 필요한 연결성을 가져야하며 거래 주문을 보내려면 거래소에 직접 연결되어야합니다. 플러그 앤 플레이 통합 : 상인은 가격 분석을 위해 Bloomberg 터미널을 사용하고, 거래를 배치하는 브로커 터미널을 사용하고, 경향 분석을 위해 Matlab 프로그램을 사용할 수 있습니다. 개별 요구에 따라 알고리즘 거래 소프트웨어는 일반적으로 사용되는 거래 도구를 통해 쉽게 플러그 앤 플레이 통합 및 사용 가능한 API를 가져야합니다. 따라서 확장 성과 통합 성이 보장됩니다. 플랫폼 독립적 프로그래밍 : 몇 가지 프로그래밍 언어에는 전용 플랫폼이 필요합니다. 예를 들어 특정 버전의 C ++은 일부 운영 체제에서만 실행될 수 있으며 Perl은 모든 운영 체제에서 실행될 수 있습니다. 거래 소프트웨어를 구축하거나 구매할 때 플랫폼 독립적 인 플랫폼 소프트웨어를 선호하고 플랫폼 독립적 언어를 지원해야합니다. 당신은 당신의 거래가 몇 달 동안 어떻게 진화 할 것인지 결코 알 수 없습니다. 두려운 물건 : "원숭이라도 마우스 버튼을 클릭하여 거래 할 수 있습니다."컴퓨터에 대한 종속성은 장님이 아니어야합니다. 후드 아래에서 진행되는 것을 이해해야하는 것은 상인입니다. 거래 소프트웨어를 구매할 때 특정 알고리즘 거래 소프트웨어의 기본 로직을 보여주는 자세한 문서를 살펴보고 시간을 들여야합니다. 완전한 블랙 박스이고 비밀 봉급 기계라고 주장하는 거래 소프트웨어를 피하십시오.
소프트웨어를 제작하는 동안 구현하고있는 것에 대해 현실적이어야하고 실패 할 수있는 시나리오에 대해 명확해야합니다. 실제 돈으로 사용하기 전에 철저히 테스트하십시오.
어디서부터 시작해야할까요?
모든 사전 준비 알고리즘 거래 소프트웨어는 일반적으로 무료 기능 제한 시험 버전 또는 전체 기능을 갖춘 제한된 시험 기간을 제공합니다. 이 재판을하는 동안 무엇이든 사기 전에 충분히 탐구하십시오. 사용 가능한 문서를 자세히 읽는 것을 잊지 마십시오.
하나를 구축하기 위해 알고리즘 트레이딩을 탐색 할 수있는 좋은 무료 소스는 Quantopian입니다. 알고리즘 거래를 테스트하고 개발할 수있는 온라인 플랫폼을 제공합니다. 개인은 기존 알고리즘을 사용자 정의하거나 사용자 정의 할 수 있으며 완전히 새로운 알고리즘을 작성할 수 있습니다. 이 플랫폼은 또한 시장 데이터에 대해 테스트 할 수있는 내장 된 알고리즘 거래 소프트웨어를 제공합니다.
결론.
알고리즘 거래 소프트웨어는 구입하는 데 많은 비용이 들며 독자적으로 개발하기가 어렵습니다. 기성품을 구입하면 신속하고 신속하게 액세스 할 수 있으며 자신 만의 건물을 구축하면 필요에 맞게 사용자 정의 할 수있는 완벽한 유연성을 확보 할 수 있습니다. 실제 현금으로 모험하기 전에, 구매 또는 구축 된 알고리즘 거래 소프트웨어의 핵심 기능을 완전히 이해해야합니다. 그렇게하지 않으면 보상하기가 어렵습니다.

No comments:

Post a Comment