알고리즘 트레이딩 전략의 성공적인 백 테스트 pdf


수익성 높은 알 고 트레이딩 전략을 만들기 위해 애 쓰고 있습니까?


거래 할 때 돈을 잃지 않으려 고하지는 않았지만 길을 따라 가면서 많은 실수가 있었기 때문에 귀하가 살았을 때 백 테스트에서의 귀하의 전략 실적이 바뀌지 않았습니다.


나는 알고리즘 트레이딩에 5 년 넘게 관여했으며 그 당시에는 큰 거래 실수를 보았습니다.


많은 시행 착오 끝에 결국 양적 무역에서의 수익성 향상의 열쇠는 열심히 노력하고 규율하며 과학적 접근법을 발견했습니다.


성공적인 알고리즘 트레이딩에서는 처음부터 수익성있는 전략을 식별하고이를 백 테스트하고 거래 비용을 줄이며 효율적으로 거래를 완전 자동화 된 방식으로 실행하는 프로세스를 알려드립니다.


양적 무역 경력에서 얼마나 멀리 떨어져 있더라도이 아이디어를 적용하여 수익성 높은 알고리즘 거래 비즈니스를 만들 수 있습니다.


200+ 페이지 이상의 알고리즘 거래 기법 파이썬 라이브러리를 사용하여 엔드 투 엔드 주식형 백 테스터를 구현하는 방법 목차를 다운로드하십시오.


즉석 PDF 전자 서적 다운로드 - 배달 대기 없음 평생 무의미한 100 % 환불 보장 - 귀하의 위험 부담 없음! 샘플 장 다운로드.


수익성있는 거래 전략을 수립하는 것은 어렵습니다. 정말 열심히.


이러한 모든 이점에도 불구하고 나는 잘못된 생각을 갖고 알고리즘 방식의 거래 시스템을 개발하는 것이 쉽지 않다고 생각합니다. 진실에서 더 멀어 질 수는 없습니다. 알 고 트레이딩으로 쉽게 재물을 얻을 길은 없습니다.


그러나 문제를 해결하고 작고 다루기 쉬운 구성 요소로 만들고 매일 시스템을 개선하기 위해 지속적으로 발전한다면 결국에는 매우 성공적으로 될 수 있습니다.


처음에는 거래를 통해 돈을 버는 것이 투쟁입니다.


이제는 지속적으로 테스트 할 수있는 새로운 거래 전략 아이디어를 제공하는 전략 파이프 라인을 만드는 습관을 구축했습니다. 내가 선택할 수있는 것이 많기 때문에 전략이 제대로 수행되지 않는다면 중요하지 않습니다.


연구, 테스트 및 실행에 대한 느린 일관된 진도가 알고리즘 거래 수익성 달성의 핵심입니다.


체계적인 접근 방식을 사용하여 전략 구성 요소를 열심히 다룰 것을 약속하십시오. 예상보다 훨씬 빨리 성공할 것입니다.


당신이 알고리즘 거래 전문가가 아니라면 어떨까요?


사실, 내가 처음 시작할 때도 아니 었어! 나는 제한 주문, 매도인 측의 매수 측 또는 막대한 손실로 인한 시장 주문을 알지 못했습니다! 그러나 나는 지난 5 년 동안 연습했으며 그 과정에서 알고리즘 거래에 대해 많은 것을 배웠습니다.


퀀트 파이낸싱과 트레이딩에 대해 알고있는 것을 배우는 것이 당신의 능력입니다. 나는 확실히 내 분야의 최고는 아니지만, 나는 수익성 높은 거래 전략 개발에 참여해 왔으며 같은 방법을 보여주기 위해 매우 열정적입니다.


당신이 알고있는 주제가 있다고 상상해보십시오. 당신이하는 것보다 그 지역에 대해 잘 모르는 사람들이 많이 있습니다. 전문가 란 연습, 훈련 및 노력을 통해옵니다. 따라서 수익성있는 알고리즘 트레이딩 전략의 일관된 세트를 형성합니다.


알고리즘 거래에서 내가 아는 모든 성공적인 사람은 시장에 대해 많이 알기 전에 시작되었습니다.


자신이 더 열심히 노력하고 전문가가되는 법을 배우기 위해 알고리즘 거래에 아직 익숙하지 않다는 사실을 이용하십시오.


저자에 관하여.


그럼 누가 이걸 뒤에 있니?


안녕! 내 이름은 Mike Halls-Moore이고 나는 QuantStart와 'Successful Algorithmic Trading'패키지 뒤에있는 녀석이다.


헤지 펀드의 양적 거래 개발자로서 일한 이래로 나는 양적 거래에 대한 열정과 자신의 포트폴리오 운영에 열중했습니다.


저는 QuantStart 커뮤니티를 시작했고 다른 사람들이 저의 실수로부터 배우고 양적 거래를 다음 단계로 이끌 수있는 수단으로 'Successful Algorithmic Trading'을 썼습니다.


어떤 주제가 책에 포함되어 있습니까?


새로운 트레이딩 전략 아이디어를 찾고 포트폴리오를 객관적으로 평가하는 방법을 배우게됩니다.


자산 가격 정보를 모두 저장하는 강력한 증권 마스터 데이터베이스를 만드는 방법을 알려 드리겠습니다.


우리는 전략적 아이디어를 철저히 테스트하여 거래하는 것을 고려하기 전에 과학적 방법을 적용 할 것입니다.


우리의 전략은 업계 수준의 성과 측정에 대해 광범위하게 테스트됩니다.


우리는 시계열 통계 방법을 사용하여 평균 회귀와 운동량을 테스트 할 것입니다.


주식 및 선물에 대한 수익성 높은 평균 회귀 전략 템플릿을 논의 할 것이며, 이를 통해 자신을 트레이드 할 수 있습니다.


Variance-at-Risk (VaR)와 같은 투자 등급 위험 관리 기법에 대해 배우게됩니다.


우리는 켈리 기준 (Kelly Criterion)과 같은 포지션 사이징 및 금전 관리 기술에 대해 광범위하게 논의 할 것입니다.


우리는 거래 포트폴리오 시스템을 기반으로 한 강력한 자동 실행 시스템을 만들고 배포 할 것입니다.


어떤 기술적 인 기술을 배울 수 있습니까?


양적 거래에 많이 사용되는 Python 과학 도구 세트에 대해 소개 할 것입니다. 우리는 NumPy, SciPy, pandas, scikit-learn 및 IPython을 사용할 것입니다.


무료 및 유료 소스에서 재무 데이터를 얻는 방법을 배우게됩니다. 우리는 주식 및 선물 데이터를 청결하게하고 지속적인 선물 계약을 맺음으로써 주식 및 선물 데이터를 다룰 것입니다.


팬더를 사용하여 전략 성과를 백 테스팅 (backtest)하고 Sharpe Ratio, 최대 드로우 다운, 드로우 다운 지속 시간 및 평균 승패와 같은 수량을 계산하는 방법을 배웁니다.


매개 변수 민감도 분석을 사용하여 수학적으로 전략을 최적화하고 결과를 시각적으로 검사하는 방법을 학습합니다. 이를 위해 pandas와 matplotlib를 IPython과 함께 사용합니다.


예측 분류 자 ​​및 일중 주식 쌍 거래에 대해 배우게됩니다. 우리는 scikit-learn을 사용하여 회귀, 무작위 포리스트 앙상블 및 비선형 SVM을 수행합니다.


파이썬으로 대화식 브로커 API에 연결하여 거래 할 수 있습니다. 현실적인 거래 비용을 계산하여 실적 통계에 반영합니다.


나에 대해 더 많이 알 수있는 곳은 어디입니까?


필자는 퀀트 트레이딩, 퀀트 커리어, 퀀트 개발, 데이터 과학 및 기계 학습을 다루는 퀀트 스타트 (QuantStart)에 100 개의 게시물을 작성했습니다. 내 거래 방법론 및 전략에 대해 자세히 알아 보려면 아카이브를 읽을 수 있습니다.


책에 만족하지 않으면 어떡하지?


성공적인 알고리즘 트레이딩이 양적 트레이딩 교육에 매우 유용하다고 생각하지만, 어떤 이유로 든 책에 100 % 만족하지 않는다면 전액 환불을 요청하는 질문은 없습니다.


그 책의 하드 카피를 얻을 수 있을까요?


아닙니다. 이 단계에서 책은 Adobe PDF 형식으로 만 제공되며, "도서 + 소프트웨어"옵션을 구입하면 코드 자체가 완벽한 Python 스크립트의 zip 파일로 제공됩니다.


어떤 패키지를 사야합니까?


이는 주로 예산에 따라 다릅니다. 완전한 소스 코드가 포함 된 책은 코드를 즉시 파고 드는 것이 가장 좋지만 책 자체에는 퀀트 거래 프로세스에 도움이 될 엄청난 양의 코드 스 니펫이 포함되어 있습니다.


연락을받을 수 있습니까?


당연하지! 이 페이지를 읽은 후에도 질문이있는 경우 연락을 취하십시오. 필요한 답을 제공하기 위해 최선을 다할 것입니다. 그러나, 당신을 도울지도 모른다 기사 명부를보십시오, 보십시오.


수학에 학위가 필요합니까?


어려운 수학에 대한 언급 없이도 책의 대부분은 아주 쉽게 따라갈 수 있습니다. 그러나 예측 및 시계열 분석에 대한 섹션에는 기본 미적분 및 선형 대수가 필요합니다.


QuantStart.


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


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


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


Michael Halls-Moore (2013 년 4 월 26 일)


이 기사에서는 Beginner 's Guide 및 Strategy Identification으로 시작된 양적 거래에 대한 시리즈를 계속합니다. 이 길고, 더 관여하는 기사는 매우 인기가 있었기 때문에이 글에서 계속해서 전략 백 테스팅에 대한 세부 사항을 제공 할 것입니다.


알고리즘 백 테스팅은 심리학, 수학, 통계, 소프트웨어 개발 및 시장 / 교환 미세 구조를 포함한 많은 분야에 대한 지식이 필요합니다. 하나의 기사에서 모든 주제를 다룰 수는 없으므로 두 개 또는 세 개의 작은 조각으로 나눌 것입니다. 이 섹션에서 우리는 무엇을 논의 할 것인가? 우선 백 테스팅을 정의한 다음 시작하는 방법에 대한 기본 사항을 설명하겠습니다. 그런 다음 양적 교역에 대한 초보자 안내서에서 다루었던 편견을 설명 할 것입니다. 다음으로 다양한 백 테스팅 소프트웨어 옵션을 비교해 보겠습니다.


다음 기사에서는 간혹 언급되거나 무시되는 전략 구현의 세부 사항을 살펴볼 것입니다. 거래 교환의 특성을 포함시켜 백 테스팅 프로세스를보다 현실적으로 만드는 방법도 고려할 것입니다. 그런 다음 거래 비용과 백 테스트 설정에서이를 정확하게 모델링하는 방법에 대해 논의 할 것입니다. 우리는 백 테스팅의 성과에 대한 논의로 끝낼 것이고 마침내 평균 반전 쌍 무역으로 알려진 일반적인 퀀텀 전략의 예를 제공 할 것입니다.


먼저 백 테스팅이 무엇인지, 왜 우리가 알고리즘 트레이딩에서 그것을 수행해야하는지에 대해 논의 해보자.


Backtesting이란 무엇입니까?


알고리즘 거래는 다른 유형의 투자 클래스와 차별화됩니다. 왜냐하면 풍부한 데이터 가용성으로 인해 과거 실적에서 미래의 성과에 대한 기대치를보다 정확하게 제공 할 수 있기 때문입니다. 이를 수행하는 프로세스를 역 테스팅 (backtesting)이라고합니다.


간단히 말해서 백 테스팅은 특정 전략 알고리즘을 과거 재무 데이터의 흐름에 노출시킴으로써 이루어지며 이는 일련의 거래 신호로 연결됩니다. 각 거래 (여기서는 두 신호의 '왕복'이라는 의미)는 관련 이익 또는 손실을 가져옵니다. 전략 백 테스트 기간 동안이 이익 / 손실이 축적되면 총 손익 ( 'P & L'또는 'PnL'이라고도 함)이 발생합니다. 그것이 "악마는 언제나 세부 사항에있다"고하지만, 이것이 아이디어의 본질입니다!


알고리즘 전략을 백 테스트하는 주요 이유는 무엇입니까?


여과 - 전략 식별에 대한 기사에서 상기 한 초기 연구 단계의 목표는 전략 파이프 라인을 설정 한 다음 특정 기준을 충족시키지 못한 전략을 필터링하는 것이 었습니다. Backtesting은 성능 요구 사항을 충족시키지 못하는 전략을 제거 할 수 있으므로 다른 필터링 메커니즘을 제공합니다. 모델링 - 백 테스트를 통해 거래 비용, 주문 라우팅, 대기 시간, 유동성 또는 기타 시장 미세 구조 문제와 같은 특정 시장 현상에 대한 새로운 모델을 테스트 할 수 있습니다. 최적화 - 전략 최적화는 편향성이 있지만 백 테스팅을 통해 전략과 관련된 매개 변수의 양 또는 값을 수정하고 성능을 다시 계산함으로써 전략의 성능을 향상시킬 수 있습니다. 검증 - 우리의 전략은 전략 파이프 라인을 통해 외부에서 공급되는 경우가 종종 있습니다. 전략을 백 테스팅하면 잘못 구현되지 않았 음을 보증 할 수 있습니다. 외부 전략에 의해 생성 된 신호에 거의 액세스하지는 않지만 Sharpe Ratio 및 Drawdown 특성과 같은 성능 메트릭에 액세스 할 수 있습니다. 따라서 우리는 그것을 우리 자신의 구현과 비교할 수 있습니다.


Backtesting은 알고리즘 거래에 많은 이점을 제공합니다. 그러나 전략을 직접 백 테스팅하는 것이 항상 가능한 것은 아닙니다. 일반적으로 전략의 빈도가 증가함에 따라 시장 및 거래소의 미세 구조 효과를 정확하게 모델링하는 것이 어려워진다. 이로 인해 신뢰성이 떨어지는 백 테스트가 발생하고 선택한 전략을보다 까다롭게 평가하게됩니다. 이것은 실행 시스템이 초 고주파 알고리즘처럼 전략 성능의 핵심 인 경우 특히 문제입니다.


불행히도, 백 테스팅은 모든 유형의 편견으로 가득 차 있습니다. 우리는 이전 기사에서 이러한 문제 중 일부를 다루었으나 이제는 심도있게 논의 할 것입니다.


전략 배점에 영향을주는 편견.


백 테스트 된 전략의 성능에 영향을 줄 수있는 많은 편견이 있습니다. 불행히도 이러한 편향은 성능을 저하시키는 것보다 성능을 부 풀리는 경향이 있습니다. 따라서 항상 전략의 실제 성과에 대한 이상적인 상한선 인 백 테스트를 고려해야합니다. 알고리즘 거래에서 편견을 제거하는 것은 거의 불가능하므로 알고리즘 전략에 대한 충분한 정보를 바탕으로 의사 결정을 내릴 수있는 최선의 방법으로 최소화해야합니다.


최적화 바이어스, 미리보기 바이어스, 생존자 편견 및 심리적 공차 바이어스와 같은 네 가지 주요 편견에 대해 논의하고 싶습니다.


최적화 바이어스.


이것은 아마 모든 backtest 편견 중에서 가장 교활한 것입니다. 백 테스트 데이터 세트의 전략 성과가 매우 매력적 일 때까지 추가 거래 매개 변수를 조정하거나 도입해야합니다. 그러나 일단 라이브가되면 전략의 성능이 크게 달라질 수 있습니다. 이 편견의 또 다른 이름은 "curve fitting"또는 "data-snooping bias"입니다.


알고리즘 전략은 종종 많은 매개 변수를 포함하기 때문에 최적화 바이어스를 제거하기가 어렵습니다. 이 경우의 "매개 변수"는 진입 / 퇴출 기준, 룩백 기간, 평균 기간 (즉, 이동 평균 평활화 매개 변수) 또는 변동성 측정 빈도 일 수 있습니다. 최적화 바이어스는 매개 변수의 수를 최소로 유지하고 트레이닝 세트의 데이터 요소 양을 늘려 최소화 할 수 있습니다. 사실, 오래된 교육 포인트는 이전의 정권 (예 : 규제 환경)에 종속 될 수 있으므로 현재 전략과 관련되지 않을 수 있으므로 후자에주의해야합니다.


이 편향을 완화하는 한 가지 방법은 민감도 분석을 수행하는 것입니다. 이는 매개 변수를 점진적으로 변경하고 성능의 "표면"을 그려야 함을 의미합니다. 매개 변수 선택에 대한 건전하고 근본적인 추론은 다른 모든 요인을 고려할 때보다 매끄러운 매개 변수 표면을 유도해야합니다. 성능이 급격히 떨어지는 경우 매개 변수가 현상을 반영하지 않고 테스트 데이터의 결과 인 경우가 많습니다. 다차원 최적화 알고리즘에 대한 방대한 문헌이 있으며 매우 활발한 연구 분야입니다. 환상적인 백 테스트 전략을 찾으면 여기에 머물러 서지 말고 마음의 뒤쪽에 두십시오!


미리보기 바이어스.


Look-Ahead 바이어스는 미래의 데이터가 실수로 시뮬레이션에서 그 데이터가 실제로 이용 가능하지 않은 지점에 포함될 때 백 테스팅 시스템에 도입됩니다. 백 테스트를 시간순으로 실행하고 시점을 $ N $로하면 $ k> 0 $ 인 $ N + k $ 점에 데이터가 포함되어 있으면 look-ahead bias가 발생합니다. Look-Ahead 바이어스 오류는 엄청나게 미묘합니다. 미리보기 바이어스를 도입하는 방법에 대한 세 가지 예가 있습니다.


기술적 인 버그 - 코드의 배열 / 벡터에는 종종 반복자 또는 인덱스 변수가 있습니다. 이러한 인덱스의 잘못된 오프셋은 0이 아닌 $ k $에 대해 $ N + k $에 데이터를 통합하여 미리보기 편향을 유발할 수 있습니다. 매개 변수 계산 - 두 가지 시계열 간의 선형 회귀와 같이 최적의 전략 매개 변수를 계산할 때 미리보기 바이어스의 또 다른 일반적인 예가 발생합니다. 전체 데이터 세트 (미래 데이터 포함)가 회귀 계수를 계산하는 데 사용되고 따라서 소급 적용을 위해 거래 전략에 소급 적용되는 경우 향후 데이터가 통합되고 미리보기 편견이 존재합니다. Maxima / Minima - 특정 거래 전략은 OHLC 데이터에 고가 또는 저가를 통합하는 것과 같이 모든 기간에 극단 치를 사용합니다. 그러나 이러한 최대 / 최소 값은 기간 만료시에만 계산할 수 있으므로이 값이 현재 기간 동안 사용되면 미리보기 바이어스가 도입됩니다. 그것들을 사용하는 모든 거래 전략에서 적어도 하나의 기간만큼 고 / 저값을 래깅 할 필요가 있습니다.


최적화 편견과 마찬가지로, 도입을 피하기 위해 매우 조심해야합니다. 종종 "라이브 거래"에서 거래 전략이 백 테스팅을 크게 하회하는 주된 이유입니다.


생존자 편견.


생존자 편견은 특히 위험한 현상이며 특정 전략 유형에 대해 상당히 과장된 성과로 이어질 수 있습니다. 특정 시점에 선택되었을 수도있는 이전 자산의 전체 유니버스를 포함하지 않는 데이터 세트에서 전략을 테스트 할 때 발생하지만 현재 시간까지 "살아남은"자산 만 고려해야합니다.


예를 들어, 2001 년 시장 추락 전과 후에 무작위로 주식을 선택하는 전략을 시험해보십시오. 일부 기술주는 파산했고, 다른 일부는 살아남을 수 있었고 심지어 번영했습니다. 우리가 시장 하락 기간을 통해 주식을 생산 한 주식에만이 전략을 제한했다면, 이미 우리에게 성공을 입증했기 때문에 생존자 편향을 도입 할 것입니다. 실제로 이것은 미래 정보가 과거 분석에 통합되므로 미리보기 편향의 또 다른 특별한 경우입니다.


전략 백 테스트에서 생존자 편향을 완화하는 두 가지 주요 방법이 있습니다.


Survivorship Bias Free Datasets - 형평 데이터의 경우에는 값이 싸지 않고 제도 기관에서 활용하는 경향이 있지만 상장 데이터를 구매할 수 있습니다. 특히 야후 파이낸스 데이터는 생존자 편견이 없으며, 이는 많은 소매업 자들에게 일반적으로 사용됩니다. 생존자 편견에 취약하지 않은 자산 클래스 (예 : 특정 상품 (및 미래 파생 상품))와 거래 할 수도 있습니다. 최근 데이터 사용 - 주식의 경우 최신 데이터 세트를 사용하면 선택한 주식 선택이 단기간에 전체 재고 상장 가능성이 줄어들 기 때문에 "생존자"에게 가중치를 적용 할 가능성이 줄어 듭니다. 현재 시점부터 데이터를 수집하여 개인 생존자 편견없는 데이터 집합을 구축하기 시작할 수도 있습니다. 3 ~ 4 년이 지난 후에는 추가 생존 전략에 대한 철저한 검증을 위해 확실한 생존자 편견이없는 주식 데이터 세트를 갖게됩니다.


우리는 이제 귀하의 거래 실적에 영향을 미칠 수있는 특정 심리적 현상을 고려할 것입니다.


심리적 인 공차 편견.


이 특별한 현상은 양적 거래의 맥락에서 종종 논의되지 않는다. 그러나 더 자유 재량 적 거래 방법에 관해서는 광범위하게 논의되고있다. 그것은 다양한 이름을 가지고 있지만 문제의 본질을 포착하기 때문에 "심리적 인 편견"이라고 부르기로했습니다. 5 년 이상의 기간에 걸쳐 백 테스트를 작성하는 경우, 상승 추세 형평성 곡선을보고, 복합 연간 수익률, 샤프 비율 및 드랍 다운 특성을 계산하고 결과에 만족할 수 있습니다. 예를 들어, 이 전략은 25 %의 최대 상대 배출량과 4 개월의 최대 배출 감소 기간을 가질 수 있습니다. 이것은 운동량 전략에 비 전형적인 것은 아니다. 전반적인 그림이 장밋빛이기 때문에 그러한 손실 기간을 용인하는 것이 쉽다는 것을 스스로에게 확신시키는 것은 간단합니다. 그러나 실제로는 훨씬 더 어렵습니다!


역 테스크에서 25 % 또는 그 이상의 역사적 감소가 발생한다면, 라이브 거래에서 비슷한 수준의 손실을 볼 수 있습니다. 이러한 삭감 기간은 심리적으로 견딜 수 없습니다. 나는 제도적 상황에서 연장 축소가 어떤 모습 일 수 있는지를 직접 목격했으며, 백 테스트가 그러한 기간이 발생할 것이라고 제안하더라도 유쾌하지 않다. 내가 "편견"이라고 불렀던 이유는 종종 그렇지 않은 전략이 연장 된 드래그 다운 시간에 거래가 중단되어 백 테스트에 비해 크게 부진 할 수 있다는 것입니다. 따라서 전략이 본질적으로 알고리즘이기는하지만 심리적 요인은 여전히 ​​수익성에 큰 영향을 줄 수 있습니다. 테이크 어웨이는 백 테스터에서 일정 비율 및 기간의 약정을 볼 경우 라이브 거래 환경에서 발생할 것으로 예상해야하며 수익성에 다시 도달하려면 인내해야합니다.


Backtesting을위한 소프트웨어 패키지.


전략 backtesting을위한 소프트웨어 경관은 광대합니다. 솔루션은 완벽하게 통합 된 기관 급의 정교한 소프트웨어부터 C ++, Python 및 R과 같은 프로그래밍 언어에 이르기까지 거의 모든 것이 처음부터 (또는 적절한 '플러그인'이 확보 된) 작성되어야합니다. 퀀트 트레이더로서 우리는 우리의 거래 기술 스택 대 개발 전략의 속도와 신뢰성을 "소유"할 수있는 균형에 관심이 있습니다. 다음은 소프트웨어 선택에 대한 주요 고려 사항입니다.


프로그래밍 기술 - 환경 선택은 대부분 소프트웨어를 프로그래밍 할 수있는 능력에 달려 있습니다. 나는 전체 스택을 제어하는 ​​것이 공급 업체 소프트웨어에 가능한 한 많이 아웃소싱하는 것보다 장기 P & L에 더 큰 효과가있을 것이라고 주장합니다. 이것은 벤더 소프트웨어에서 해결할 수없는 외부 버그 나 특이점을 가질 수있는 단점이 있기 때문입니다. 그렇지 않으면 "기술 스택"을보다 잘 제어 할 수 있다면 쉽게 해결할 수 있습니다. 또한 생산성, 라이브러리 가용성 및 실행 속도 사이에서 올바른 균형을 유지하는 환경이 필요합니다. 나는 아래에 나 자신의 개인적인 추천을한다. 실행 기능 / 브로커 상호 작용 - Tradestation과 같은 특정 백 테스팅 소프트웨어는 중개 회사와 직접 연결됩니다. 나는 거래 비용을 줄이는 것이 종종 더 높은 Sharpe 비율을 얻는 큰 요소가되기 때문에이 접근법의 팬이 아니다. 특정 브로커에 묶여 있다면 (Tradestation은 이것을 수행하도록 강제합니다.) 필요가 생기면 새로운 소프트웨어 (또는 새 브로커)로 전환하는 것이 더 힘들어집니다. 인터랙티브 중개인은 약간 둔한 인터페이스를 가지고 있지만 견고한 API를 제공합니다. 커스터마이징 - MATLAB이나 Python과 같은 환경은 알 고 전략을 만들 때 상당한 유연성을 제공하여 상상할 수있는 거의 모든 수학 연산에 환상적인 라이브러리를 제공 할뿐만 아니라 필요한 경우 광범위한 커스터마이즈를 허용합니다. 전략의 복잡성 - 특정 소프트웨어는 엄청난 규모의 복잡성이나 수학적 복잡성 때문에 잘려나 가지 않습니다. Excel은 이러한 소프트웨어 중 하나입니다. 보다 단순한 전략에 유리하지만 많은 자산이나 복잡한 알고리즘을 빠르게 처리 할 수는 없습니다. 편향 최소화 - 소프트웨어 또는 데이터의 특정 부분이 거래 편향에 더 많이 도움이 되는가? 모든 기능을 직접 만들고 싶다면 편견을 유발할 수있는 버그가 있는지 확인해야합니다. 개발 속도 - 백 테스트 엔진을 구현하는 데 수개월이 걸릴 필요가 없습니다. 프로토 타이핑은 몇 주 밖에 걸리지 않습니다. 귀하의 소프트웨어가 귀하의 진보를 방해하지 않는지, 단지 몇 퍼센트의 실행 속도를 얻는 지 확인하십시오. C ++은 "방안의 코끼리"입니다! 실행 속도 - 전략이 실행 적시성 (HFT / UHFT 에서처럼)에 완전히 의존하는 경우 C 또는 C ++와 같은 언어가 필요합니다. 그러나이 기사의 범위를 벗어나는 이러한 도메인에 대한 Linux 커널 최적화 및 FPGA 사용에 대해 조사 할 예정입니다. 비용 - 알고리즘 거래 전략을 프로그래밍 할 수있는 많은 소프트웨어 환경은 완전히 무료이며 오픈 소스입니다. 사실, 많은 헤지 펀드는 전체 algo trading 스택을 위해 오픈 소스 소프트웨어를 사용합니다. 또한 Excel과 MATLAB은 모두 상대적으로 저렴하며 각각 무료 대안이 있습니다.


이제 우리는 소프트웨어 인프라를 선택해야하는 기준을 나열 했으므로 인기있는 패키지와 비교 방법을 살펴보고자합니다.


참고 : 대부분의 소매업 종사자 및 소프트웨어 개발자가 사용할 수있는 소프트웨어 만 포함 할 예정입니다. 이는이 사이트의 독자층이기 때문입니다. 기관용 등급 도구와 같은 다른 소프트웨어를 사용할 수는 있지만 소매 가격 환경에서 효과적으로 사용하려면이 비용이 너무 비싸고 개인적으로 경험이 없습니다.


라이센스 1,000 달러.


전략에 따라 서로 다른 소프트웨어 패키지가 필요합니다. HFT 및 UHFT 전략은 C / C ++로 작성되며 (요즘은 GPU 및 FPGA에서 수행되는 경우가 많음), 반면에 저비용 방향성 지분 전략은 TradeStation에서 구현하기 쉽습니다. 소프트웨어 / 중개.


내 개인적인 선호는 Python이 내 요구와 전략에 맞는 맞춤화, 개발 속도, 테스트 기능 및 실행 속도를 제공하기 때문입니다. 더 빠른 것이 필요한 경우 Python 프로그램에서 직접 C ++로 "끌어 들일"수 있습니다. 많은 퀀트 트레이더가 선호하는 한 가지 방법은 Python에서 전략을 프로토 타입하고 느린 실행 섹션을 반복적으로 C ++로 변환하는 것입니다. 결국 전체 algo는 C ++로 작성되었으며 "교역 용으로 남겨 둘 수 있습니다"!


backtesting에 대한 다음 몇 기사에서는 알고리즘 거래 backtesting 시스템의 구현을 둘러싼 특정 문제와 거래 교환의 효과를 통합하는 방법을 살펴볼 것입니다. 전략 성과 측정에 대해 논의하고 마지막으로 예제 전략으로 결론을 맺을 것입니다.


양적 거래 시작하기?


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


1. 퀀트 트레이딩 레슨.


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


2. 모든 최신 내용.


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


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


알고리즘 트레이딩 전략의 성공적인 백 테스팅, Part 1.


이 기사는 Beginner의 Guide and Strategy Identification에서 시작된 양적 거래 시리즈를 계속합니다. 이 길고 관련성이 높은 기사는 모두 매우 인기가 있었기 때문에이 글에서 계속해서 전략 백 테스팅에 대한 세부 정보를 제공 할 것입니다. 알고리즘 백 테스팅은 심리학, 수학, 통계, 소프트웨어 개발 및 시장 / 교환 미세 구조를 포함한 많은 분야에 대한 지식이 필요합니다. 하나의 기사에서 모든 주제를 다루기를 기대할 수 없었기 때문에 두 개 또는 세 개의 작은 조각으로 나눌 것입니다. 이 섹션에서 우리는 무엇을 논의 할 것인가? 우선 백 테스팅을 정의한 다음 시작하는 방법에 대한 기본 사항을 설명합니다. 그런 다음 초보자가 양적 교역 가이드에서 언급 한 편견에 대해 설명해 드리겠습니다. 다음으로 다양한 백 테스팅 소프트웨어 옵션을 비교해 보겠습니다. 다음 기사에서는 간혹 언급되거나 무시되는 전략 구현의 세부 사항을 살펴볼 것입니다. 우리는 또한 거래 교환의 특이성을 포함시킴으로써 백 테스팅 프로세스를보다 현실적으로 만드는 방법을 고려할 것입니다. 그런 다음 거래 비용과 백 테스트 설정에서이를 정확하게 모델링하는 방법에 대해 논의 할 것입니다. 우리는 백 테스팅의 성과에 대한 논의로 끝낼 것이고 마침내 평균 반전 쌍 무역으로 알려진 일반적인 퀀텀 전략의 예를 제공 할 것입니다. 우리는 backtesting이 무엇이고 알고리즘 트레이딩에서 왜 그것을 수행해야하는지에 대해 논의함으로써 시작하자.


Backtesting이란 무엇입니까?


알고리즘 거래는 다른 유형의 투자 클래스와 차별화됩니다. 왜냐하면 풍부한 데이터 가용성으로 인해 과거 실적에서 미래의 성과에 대한 기대치를보다 정확하게 제공 할 수 있기 때문입니다. 이를 수행하는 프로세스를 역 테스팅 (backtesting)이라고합니다. 간단히 말해서 백 테스팅은 특정 전략 알고리즘을 과거 재무 데이터의 흐름에 노출시킴으로써 이루어지며 이는 일련의 거래 신호로 연결됩니다. 두 가지 신호 중 왕복 여행을 의미하는 각 거래에는 관련 이익 또는 손실이 있습니다. 전략 백 테스트 기간 동안이 이익 / 손실이 누적되면 총 손익 (P & L 및 PnL이라고도 함)이 발생합니다. 그게 아이디어의 본질입니다. 물론 악마는 항상 세부 사항에 있습니다. 알고리즘 전략을 백 테스트하는 주요 이유는 무엇입니까?


여과 & # 8211; Strategy Identification에 대한 기사를 상기 해보면 초기 연구 단계에서의 목표는 전략 파이프 라인을 설정 한 다음 특정 기준을 충족시키지 못한 전략을 필터링하는 것이 었습니다. Backtesting은 성능 요구를 충족시키지 못하는 전략을 제거 할 수 있으므로 다른 필터링 메커니즘을 제공합니다. 모델링 & # 8211; 백 테스트를 통해 거래 비용, 주문 라우팅, 대기 시간, 유동성 또는 기타 시장 미세 구조 문제와 같은 특정 시장 현상에 대한 새로운 모델을 테스트 할 수 있습니다. 최적화 & # 8211; 전략 최적화는 편향성이 있지만 백 테스팅을 통해 전략과 관련된 매개 변수의 양 또는 값을 수정하고 성능을 다시 계산함으로써 전략의 성능을 향상시킬 수 있습니다. 확인 & # 8211; 우리의 전략은 대개 전략 파이프 라인을 통해 외부에서 공급됩니다. 전략을 백 테스팅하면 잘못 구현되지 않았 음을 보증 할 수 있습니다. 외부 전략에 의해 생성 된 신호에 거의 액세스하지는 않지만 Sharpe Ratio 및 Drawdown 특성과 같은 성능 메트릭에 액세스 할 수 있습니다. 따라서 우리는 그것을 우리 자신의 구현과 비교할 수 있습니다.


Backtesting은 알고리즘 거래에 많은 이점을 제공합니다. 그러나 전략을 직접 백 테스팅하는 것이 항상 가능한 것은 아닙니다. 일반적으로 전략의 빈도가 증가함에 따라 시장 및 거래소의 미세 구조 효과를 정확하게 모델링하는 것이 어려워진다. 이로 인해 신뢰성이 떨어지는 백 테스트가 발생하고 선택한 전략을보다 까다롭게 평가하게됩니다. 이것은 실행 시스템이 초 고주파 알고리즘처럼 전략 성능의 핵심 인 경우 특히 문제입니다. 불행히도, 백 테스팅은 모든 유형의 편견으로 가득 차 있습니다. 우리는 이전 기사에서 이러한 문제 중 일부를 다루었으나 이제는 심도있게 논의 할 것입니다.


전략 배점에 영향을주는 편견.


백 테스트 된 전략의 성능에 영향을 줄 수있는 많은 편견이 있습니다. 불행히도 이러한 편향은 성능을 저하시키는 것보다 성능을 부 풀리는 경향이 있습니다. 따라서 항상 전략의 실제 성과에 대한 이상적인 상한선 인 백 테스트를 고려해야합니다. 알고리즘 거래에서 편견을 제거하는 것은 거의 불가능하므로 알고리즘 전략에 대한 충분한 정보를 바탕으로 의사 결정을 내릴 수있는 최선의 방법으로 최소화해야합니다. 최적화 바이어스, 미리보기 바이어스, 생존자 편견 및 심리적 공차 바이어스와 같은 네 가지 주요 편견에 대해 논의하고 싶습니다.


최적화 바이어스.


이것은 아마 모든 backtest 편견 중에서 가장 교활한 것입니다. 백 테스트 데이터 세트의 전략 성과가 매우 매력적 일 때까지 추가 거래 매개 변수를 조정하거나 도입해야합니다. 그러나 일단 라이브가되면 전략의 성능이 크게 달라질 수 있습니다. 이 바이어스의 또 다른 이름은 '곡선 맞춤'입니다. 또는 데이터 스누핑 바이어스 & # 8221; 알고리즘 전략은 종종 많은 매개 변수를 포함하기 때문에 최적화 바이어스를 제거하기가 어렵습니다. & # 8220; 매개 변수 & # 8221; 이 경우 엔트리 / 종료 기준, 룩백 기간, 평균 기간 (즉, 이동 평균 평활화 파라미터) 또는 변동성 측정 빈도 일 수있다. 최적화 바이어스는 매개 변수의 수를 최소로 유지하고 트레이닝 세트의 데이터 요소 양을 늘려 최소화 할 수 있습니다. In fact, one must also be careful of the latter as older training points can be subject to a prior regime (such as a regulatory environment) and thus may not be relevant to your current strategy. One method to help mitigate this bias is to perform a sensitivity analysis . This means varying the parameters incrementally and plotting a “surface” of performance. Sound, fundamental reasoning for parameter choices should, with all other factors considered, lead to a smoother parameter surface. If you have a very jumpy performance surface, it often means that a parameter is not reflecting a phenomena and is an artefact of the test data. There is a vast literature on multi-dimensional optimisation algorithms and it is a highly active area of research. I won’t dwell on it here, but keep it in the back of your mind when you find a strategy with a fantastic backtest!


Look-Ahead Bias.


Look-ahead bias is introduced into a backtesting system when future data is accidentally included at a point in the simulation where that data would not have actually been available. If we are running the backtest chronologically and we reach time point N , then look-ahead bias occurs if data is included for any point N + k , where k > 0 . Look-ahead bias errors can be incredibly subtle. Here are three examples of how look-ahead bias can be introduced:


Technical Bugs – Arrays/vectors in code often have iterators or index variables. Incorrect offsets of these indices can lead to a look-ahead bias by incorporating data at N + k for non-zero k . Parameter Calculation – Another common example of look-ahead bias occurs when calculating optimal strategy parameters, such as with linear regressions between two time series. If the whole data set (including future data) is used to calculate the regression coefficients, and thus retroactively applied to a trading strategy for optimisation purposes, then future data is being incorporated and a look-ahead bias exists. Maxima/Minima – Certain trading strategies make use of extreme values in any time period, such as incorporating the high or low prices in OHLC data. However, since these maximal/minimal values can only be calculated at the end of a time period, a look-ahead bias is introduced if these values are used - during - the current period. It is always necessary to lag high/low values by at least one period in any trading strategy making use of them.


생존자 편견.


Survivorship bias is a particularly dangerous phenomenon and can lead to significantly inflated performance for certain strategy types. It occurs when strategies are tested on datasets that do not include the full universe of prior assets that may have been chosen at a particular point in time, but only consider those that have “survived” to the current time. As an example, consider testing a strategy on a random selection of equities before and after the 2001 market crash. Some technology stocks went bankrupt, while others managed to stay afloat and even prospered. If we had restricted this strategy only to stocks which made it through the market drawdown period, we would be introducing a survivorship bias because they have already demonstrated their success to us. In fact, this is just another specific case of look-ahead bias, as future information is being incorporated into past analysis. There are two main ways to mitigate survivorship bias in your strategy backtests:


Survivorship Bias Free Datasets – In the case of equity data it is possible to purchase datasets that include delisted entities, although they are not cheap and only tend to be utilised by institutional firms. In particular, Yahoo Finance data is NOT survivorship bias free, and this is commonly used by many retail algo traders. One can also trade on asset classes that are not prone to survivorship bias, such as certain commodities (and their future derivatives). Use More Recent Data – In the case of equities, utilising a more recent data set mitigates the possibility that the stock selection chosen is weighted to “survivors”, simply as there is less likelihood of overall stock delisting in shorter time periods. One can also start building a personal survivorship-bias free dataset by collecting data from current point onward. After 3-4 years, you will have a solid survivorship-bias free set of equities data with which to backtest further strategies. We will now consider certain psychological phenomena that can influence your trading performance.


We will now consider certain psychological phenomena that can influence your trading performance.


Psychological Tolerance Bias.


This particular phenomena is not often discussed in the context of quantitative trading. However, it is discussed extensively in regard to more discretionary trading methods. It has various names, but I’ve decided to call it “psychological tolerance bias” because it captures the essence of the problem. When creating backtests over a period of 5 years or more, it is easy to look at an upwardly trending equity curve, calculate the compounded annual return, Sharpe ratio and even drawdown characteristics and be satisfied with the results. As an example, the strategy might possess a maximum relative drawdown of 25% and a maximum drawdown duration of 4 months. This would not be atypical for a momentum strategy. It is straightforward to convince oneself that it is easy to tolerate such periods of losses because the overall picture is rosy. However, in practice, it is far harder! If historical drawdowns of 25% or more occur in the backtests, then in all likelihood you will see periods of similar drawdown in live trading. These periods of drawdown are psychologically difficult to endure. I have observed first hand what an extended drawdown can be like, in an institutional setting, and it is not pleasant – even if the backtests suggest such periods will occur. The reason I have termed it a “bias” is that often a strategy which would otherwise be successful is stopped from trading during times of extended drawdown and thus will lead to significant underperformance compared to a backtest. Thus, even though the strategy is algorithmic in nature, psychological factors can still have a heavy influence on profitability. The takeaway is to ensure that if you see drawdowns of a certain percentage and duration in the backtests, then you should expect them to occur in live trading environments, and will need to persevere in order to reach profitability once more.


Software Packages for Backtesting.


The software landscape for strategy backtesting is vast. Solutions range from fully-integrated institutional grade sophisticated software through to programming languages such as C++, Python and R where nearly everything must be written from scratch (or suitable ‘plugins’ obtained). As quant traders we are interested in the balance of being able to “own” our trading technology stack versus the speed and reliability of our development methodology. Here are the key considerations for software choice:


Programming Skill – The choice of environment will in a large part come down to your ability to program software. I would argue that being in control of the total stack will have a greater effect on your long term P&L than outsourcing as much as possible to vendor software. This is due to the downside risk of having external bugs or idiosyncrasies that you are unable to fix in vendor software, which would otherwise be easily remedied if you had more control over your “tech stack”. You also want an environment that strikes the right balance between productivity, library availability and speed of execution. I make my own personal recommendation below. Execution Capability/Broker Interaction – Certain backtesting software, such as Tradestation, ties in directly with a brokerage. I am not a fan of this approach as reducing transaction costs are often a big component of getting a higher Sharpe ratio. If you’re tied into a particular broker (and Tradestation “forces” you to do this), then you will have a harder time transitioning to new software (or a new broker) if the need arises. Interactive Brokers provide an API which is robust, albeit with a slightly obtuse interface. Customisation – An environment like MATLAB or Python gives you a great deal of flexibility when creating algo strategies as they provide fantastic libraries for nearly any mathematical operation imaginable, but also allow extensive customisation where necessary. Strategy Complexity – Certain software just isn’t cut out for heavy number crunching or mathematical complexity. Excel is one such piece of software. While it is good for simpler strategies, it cannot really cope with numerous assets or more complicated algorithms, at speed. Bias Minimisation – Does a particular piece of software or data lend itself more to trading biases? You need to make sure that if you want to create all the functionality yourself, that you don’t introduce bugs which can lead to biases. Speed of Development – One shouldn’t have to spend months and months implementing a backtest engine. Prototyping should only take a few weeks. Make sure that your software is not hindering your progress to any great extent, just to grab a few extra percentage points of execution speed. C++ is the “elephant in the room” here! Speed of Execution – If your strategy is completely dependent upon execution timeliness (as in HFT/UHFT) then a language such as C or C++ will be necessary. However, you will be verging on Linux kernel optimisation and FPGA usage for these domains, which is outside the scope of this article! Cost – Many of the software environments that you can program algorithmic trading strategies with are completely free and open source. In fact, many hedge funds make use of open source software for their entire algo trading stacks. In addition, Excel and MATLAB are both relatively cheap and there are even free alternatives to each.


Now that we have listed the criteria with which we need to choose our software infrastructure, I want to run through some of the more popular packages and how they compare: Note: I am only going to include software that is available to most retail practitioners and software developers, as this is the readership of the site. While other software is available such as the more institutional grade tools, I feel these are too expensive to be effectively used in a retail setting and I personally have no experience with them.


Description : WYSIWYG (what-you-see-is-what-you-get) spreadsheet software. Extremely widespread in the financial industry. Data and algorithm are tightly coupled. Execution : Yes, Excel can be tied into most brokerages. Customisation : VBA macros allow more advanced functionality at the expense of hiding implementation. Strategy Complexity : More advanced statistical tools are harder to implement as are strategies with many hundreds of assets. Bias Minimisation : Look-ahead bias is easy to detect via cell-highlighting functionality (assuming no VBA). Development Speed : Quick to implement basic strategies. Execution Speed : Slow execution speed – suitable only for lower-frequency strategies. Cost : Cheap or free (depending upon license). Alternatives : OpenOffice.


Description : Programming environment originally designed for computational mathematics, physics and engineering. Very well suited to vectorised operations and those involving numerical linear algebra. Provides a wide array of plugins for quant trading. In widespread use in quantitative hedge funds. Execution : No native execution capability, MATLAB requires a separate execution system. Customisation : Huge array of community plugins for nearly all areas of computational mathematics. Strategy Complexity : Many advanced statistical methods already available and well-tested. Bias Minimisation : Harder to detect look-ahead bias, requires extensive testing. Development Speed : Short scripts can create sophisticated backtests easily. Execution Speed : Assuming a vectorised/parallelised algorithm, MATLAB is highly optimised. Poor for traditional iterated loops. Cost :


Description : High-level language designed for speed of development. Wide array of libraries for nearly any programmatic task imaginable. Gaining wider acceptance in hedge fund and investment bank community. Not quite as fast as C/C++ for execution speed. Execution : Python plugins exist for larger brokers, such as Interactive Brokers. Hence backtest and execution system can all be part of the same “tech stack”. Customisation : Python has a very healthy development community and is a mature language. NumPy/SciPy provide fast scientific computing and statistical analysis tools relevant for quant trading. Strategy Complexity: Many plugins exist for the main algorithms, but not quite as big a quant community as exists for MATLAB. Bias Minimisation : Same bias minimisation problems exist as for any high level language. Need to be extremely careful about testing. Development Speed : Pythons main advantage is development speed, with robust in built in testing capabilities. Execution Speed : Not quite as fast as C++, but scientific computing components are optimised and Python can talk to native C code with certain plugins. Cost : Free/Open Source Alternatives : Ruby, Erlang, Haskell.


Description : Environment designed for advanced statistical methods and time series analysis. Wide array of specific statistical, econometric and native graphing toolsets. Large developer community. Execution : R possesses plugins to some brokers, in particular Interactive Brokers. Thus an end-to-end system can written entirely in R. Customisation : R can be customised with any package, but its strengths lie in statistical/econometric domains. Strategy Complexity : Mostly useful if performing econometric, statistical or machine-learning strategies due to available plugins. Bias Minimisation : Similar level of bias possibility for any high-level language such as Python or C++. Thus testing must be carried out. Development Speed : R is rapid for writing strategies based on statistical methods. Execution Speed : R is slower than C++, but remains relatively optimised for vectorised operations (as with MATLAB). Cost : Free/Open Source Alternatives : SPSS, Stata.


Description : Mature, high-level language designed for speed of execution. Wide array of quantitative finance and numerical libraries. Harder to debug and often takes longer to implement than Python or MATLAB. Extremely prevalent in both the buy - and sell-side. Execution : Most brokerage APIs are written in C++ and Java. Thus many plugins exist. Customisation : C/C++ allows direct access to underlying memory, hence ultra-high frequency strategies can be implemented. Strategy Complexity : C++ STL provides wide array of optimised algorithms. Nearly any specialised mathematical algorithm possesses a free, open-source C/C++ implementation on the web. Bias Minimisation : Look-ahead bias can be tricky to eliminate, but no harder than other high-level language. Good debugging tools, but one must be careful when dealing with underlying memory. Development Speed : C++ is quite verbose compared to Python or MATLAB for the same algorithmm. More lines-of-code (LOC) often leads to greater likelihood of bugs. Execution Speed : C/C++ has extremely fast execution speed and can be well optimised for specific computational architectures. This is the main reason to utilise it. Cost : Various compilers: Linux/GCC is free, MS Visual Studio has differing licenses. Alternatives : C#, Java, Scala Different strategies will require different software packages. HFT and UHFT strategies will be written in C/C++ (these days they are often carried out on GPUs and FPGAs), whereas low-frequency directional equity strategies are easy to implement in TradeStation, due to the “all in one” nature of the software/brokerage. My personal preference is for Python as it provides the right degree of customisation, speed of development, testing capability and execution speed for my needs and strategies. If I need anything faster, I can “drop in” to C++ directly from my Python programs. One method favoured by many quant traders is to prototype their strategies in Python and then convert the slower execution sections to C++ in an iterative manner. Eventually the entire algo is written in C++ and can be “left alone to trade”! In the next few articles on backtesting we will take a look at some particular issues surrounding the implementation of an algorithmic trading backtesting system, as well as how to incorporate the effects of trading exchanges. We will discuss strategy performance measurement and finally conclude with an example strategy.


저자 소개 Mike Halls-Moore.


Michael은 University of Warwick에서 수학 석사 학위를 받고 Fluid Dynamics의 Imperial College London에서 박사 학위를 받았으며 런던의 Mayfair에서 지난 몇 년간 양적 거래 개발자로 헤지 펀드에서 일했습니다. 그는 이제 연구, 개발, backtesting 및 intraday 알고리즘 거래 전략의 구현에 시간을 보낸다.


관련 게시물.


부서진 전략 또는 시장 변화 : 실적 저조 여부 조사.


어떤 작품을 찾았는지, 그리고 작동하지 않는 것.


주식 곡선 거래 & # 038; 을 넘어서.


인기 게시물.


2013 년 Connors 2 기간 RSI 업데이트.


이 단순한 지표는 돈을 다시 벌어들입니다.


아이비 포트폴리오.


Simple Gap 전략 개선, Part 1.


Capital Evolution LLC의 저작권 © 2017. - Thrive Themes에 의해 설계된 | WordPress에 의해 구동.


다시 로그인하십시오. 로그인 페이지가 새 창에서 열립니다. 로그인 한 후 닫고이 페이지로 돌아갈 수 있습니다.


Algorithmic Trading Strategies, Paradigms and Modelling Ideas.


‘Looks can be deceiving,’ a wise person once said. The phrase holds true for Algorithmic Trading Strategies. The term Algorithmic trading strategies might sound very fancy or too complicated. However, the concept is very simple to understand, once the basics are clear. In this article, I will be telling you about algorithmic trading strategies with some interesting examples.


If you look at it from the outside, an algorithm is just a set of instructions or rules. These set of rules are then used on a stock exchange to automate the execution of orders without human intervention. This concept is called Algorithmic Trading.


Let me start with a very simple trading strategy. Those who are already into trading would know about S. M.A and for those who don’t; S. M.A is Simple Moving Average. S. M.A can be calculated using any predefined and fixed number of days. An algorithmic trading strategy based on S. M.A can be simplified in these four simple steps:


Calculate 5 day SMA Calculate 20 day SMA Take a long position when the 5 day SMA is larger than or equal to 20 day SMA Take a short position when the 5 day SMA is smaller than 20 day SMA.


We refer to this algorithmic trading strategy as Moving Average Crossover Strategy . This was just a simple example. Now don’t get down to thinking that it is all going to be a bed of roses. Even if it were, then be prepared for the thorns. In everyday trading, far more complex trading algorithms are used to generate algorithmic trading strategies.


All the algorithmic trading strategies that are being used today can be classified broadly into the following categories:


Momentum/Trend Following Arbitrage Statistical Arbitrage Market Making.


Let me go into some detail.


Momentum based Strategies.


Assuming that there is a particular trend in the market. As an algo trader, you are following that trend. Further to our assumption, the markets fall within the week. Now, you can use stats to determine if this trend is going to continue. Or if it will change in the coming weeks. Accordingly, you will make your next move. You have based your algorithmic trading strategy on the market trends which you determined by using statistics.


This method of following trends is called Momentum Based Strategy.


There are numerous ways to implement this algorithmic trading strategy and I have discussed this in detail in one of our previous articles called “Methodology of Quantifying News for Automated Trading”


If we assume that a pharma-corp is to be bought by another company, then the stock price of our corp could go up. This is triggered by the acquisition which is a corporate event. If you are planning to invest based on the pricing inefficiencies that may happen during a corporate event (before or after), then you are using an event-driven strategy. Bankruptcy, acquisition, merger, spin-offs etc could be the event that drives such kind of an investment strategy.


These strategies can be market neutral and used by hedge fund and proprietary traders widely.


Statistical Arbitrage.


When an arbitrage opportunity arises because of misquoting in prices, it can be very advantageous to algo trading strategy. Although such opportunities exist for a very short duration as the prices in the market get adjusted quickly. And that’s why this is the best use of algorithmic trading strategies, as an automated machine can track such changes instantly.


For instance, if Apple’s price falls under $1 then Microsoft will fall by $0.5 but Microsoft has not fallen, so you will go and sell Microsoft to make a profit. You can read about the common misconceptions people have about Statistical Arbitrage here.


Market Making.


To understand Market making, let me first talk about Market Makers.


According to Wikipedia:


A market maker or liquidity provider is a company, or an individual, that quotes both a buy and a sell price in a financial instrument or commodity held in inventory, hoping to make a profit on the bid-offer spread, or turn.


Market making provides liquidity to securities which are not frequently traded on the stock exchange. The market maker can enhance the demand-supply equation of securities. 내가 한 가지 예를 들어 보겠다.


Let’s assume you have Martin, a market maker, who buys for Rs. 500 from the market and sell it at 505. He will give you a bid-ask quote of Rs. 505-500. The profit of Rs. 5 cannot be sold or exchanged for cash without substantial loss in value. When Martin takes a higher risk then the profit is also higher.


I found Michael Lewis’ book ‘Flash Boys’ in Indian Bull Market pretty interesting and it talks about liquidity, market making and HFT in great detail. Check it out after you finish reading this article.


Since you will need to be analytical & quantitative while getting into or upgrading to algorithmic trading it is imperative to learn programming (some if not all) and build foolproof systems and execute right algorithmic trading strategy . Reading this article on Automated Trading with Interactive Brokers using Python will be very beneficial for you. You can read the article here.


Paradigms & Modeling Ideas.


Now that I have introduced you to algorithmic trading strategies, I will be throwing some light on the strategy paradigms and modeling ideas pertaining to each strategy.


Market Making Statistical Arbitrage Momentum Machine Learning Based.


Market Making.


As I had mentioned earlier, the primary objective of Market making is to infuse liquidity in securities that are not traded on stock exchanges. In order to measure the liquidity, we take the bid-ask spread and trading volumes into consideration.


The trading algorithms tend to profit from the bid-ask spread. I will be referring to our buddy, Martin, again in this section. Martin being a market maker is a liquidity provider who can quote on both buy and sell side in a financial instrument hoping to profit from the bid-offer spread. Martin will accept the risk of holding the securities for which he has quoted the price for and once the order is received, he will often immediately sell from his own inventory. He might seek an offsetting offer in seconds and vice versa.


When it comes to illiquid securities, the spreads are usually higher and so are the profits. Martin will take a higher risk in this case. Several segments in the market lack investor interest due to lack of liquidity as they are unable to gain exit from several small - and mid-cap stocks at any given point in time.


Market Makers like Martin are helpful as they are always ready to buy and sell at the price quoted by them. In fact, much of high frequency trading (HFT) is passive market making. The strategies are present on both sides of the market (often simultaneously) competing with each other to provide liquidity to those who need.


So, when is this strategy most profitable?


This strategy is profitable as long as the model accurately predicts the future price variations.


Modeling ideas based on this Paradigm.


The bid-ask spread and trade volume can be modeled together to get the liquidity cost curve which is the fee paid by the liquidity taker. If the liquidity taker only executes orders at the best bid and ask, the fee will be equal to the bid ask spread times the volume. When the traders go beyond best bid and ask taking more volume, the fee becomes a function of the volume as well.


Trade volume is difficult to model as it depends on the liquidity takers execution strategy. The objective should be to find a model for trade volumes that is consistent with price dynamics. Market making models are usually based on one of the two:


The first focuses on inventory risk. The model is based on preferred inventory position and prices based on the risk appetite. The second is based on adverse selection which distinguishes between informed and noise trades. Noise trades do not possess any view on the market whereas informed trades do. When the view of the liquidity taker is short term, its aim is to make short term profit utilizing the statistical edge. In the case of long term view, the objective is to minimize the transaction cost. The long-term strategies and liquidity constraints can be modeled as noise around the short-term execution strategies.


To know more about Market Makers, you can check out this interesting article on QuantInsti’s blog.


Statistical Arbitrage.


If Market making is the strategy that makes use of the bid-ask spread, Statistical Arbitrage seeks to profit from statistical mispricing of one or more assets based on the expected value of these assets.


A more academic way to explain statistical arbitrage is to spread the risk among thousand to million trades in a very short holding time to, expecting to gain profit from the law of large numbers. Statistical Arbitrage Algorithms are based on mean reversion hypothesis, mostly as a pair.


Pairs trading is one of the several strategies collectively referred to as Statistical Arbitrage Strategies. In pairs trade strategy, stocks that exhibit historical co-movement in prices are paired using fundamental or market-based similarities. The strategy builds upon the notion that the relative prices in a market are in equilibrium, and that deviations from this equilibrium eventually will be corrected.


When one stock outperforms the other, the outperformer is sold short and the other stock is bought long with the expectation that the short term diversion will end in convergence. This often hedges market risk from adverse market movements i. e. makes the strategy beta neutral. However, the total market risk of a position depends on the amount of capital invested in each stock and the sensitivity of stocks to such risk.


Momentum Strategies seek to profit from the continuance of existing trend by taking advantage of market swings.


“In simple words, buy high and sell higher and vice versa.”


And how do we achieve this?


In this particular algo-trading strategy we will take short-term positions in stocks that are going up or down until they show signs of reversal. It is counter-intuitive to almost all other well-known strategies. Value investing is generally based on long-term reversion to mean whereas momentum investing is based on the gap in time before mean reversion occurs.


Momentum is chasing performance, but in a systematic way taking advantage of other performance chasers who are making emotional decisions. There are usually two explanations given for any strategy that has been proven to work historically, either the strategy is compensated for the extra risk that it takes or there are behavioral factors due to which premium exists.


There is a long list of behavioral biases and emotional mistakes that investors exhibit due to which momentum works. However, this is easier said than done as trends don’t last forever and can exhibit swift reversals when they peak and come to an end. Momentum trading carries a higher degree of volatility than most other strategies and tries to capitalize on the market volatility. It is important to time the buys and sells correctly to avoid losses by using proper risk management techniques and stop losses. Momentum investing requires proper monitoring and appropriate diversification to safeguard against such severe crashes.


Firstly, you should know how to detect Price momentum or the trends. As you are already into trading, you know that trends can be detected by following stocks and ETFs that have been continuously going up for days, weeks or even several months in a row. For instance, identify the stocks trading within 10% of their 52 weeks high or look at the percentage price change over the last 12 or 24 weeks. Similarly to spot a shorter trend, include a shorter term price change.


If you remember, back in 2008, the oil and energy sector was continuously ranked as one of the top sectors even while it was collapsing. We can also look at earnings to understand the movements in stock prices. Strategies based on either past returns (“price momentum strategies”) or on earnings surprise (known as “earnings momentum strategies”) exploit market under-reaction to different pieces of information. An earnings momentum strategy may profit from the under-reaction to information related to short-term earnings. Similarly, a price momentum strategy may profit from market’s slow response to a broader set of information including longer-term profitability.


Machine Learning based.


In Machine Learning based trading, algorithms are used to predict the range for very short term price movements at a certain confidence interval. The advantage of using Artificial Intelligence (AI) is that humans develop the initial software and the AI itself develops the model and improves it over time. A large number of funds rely on computer models built by data scientists and quants but they’re usually static, i. e. they don’t change with the market. ML based models on the other hand can analyze large amounts of data at high speed and improve themselves through such analysis.


A form of machine leaning called “Bayesian networks” can be used to predict market trends while utilizing a couple of machines. An AI which includes techniques such as evolutionary computation (which is inspired by genetics) and deep learning might run across hundreds or even thousands of machines. It can create a large and random collection of digital stock traders and test their performance on historical data. It then picks the best performers and uses their style/patterns to create a new of evolved traders. This process repeats multiple times and a digital trader that can fully operate on it’s own is created.


This process repeats multiple times and a digital trader that can fully operate on it’s own is created.


These were some important strategy paradigms and modelling ideas. Next, we will go through the step by step procedure to build a trading strategy.


You can learn these Paradigms in great detail in QuantInsti’s Executive Programme in Algorithmic Trading (EPAT) , one of the most extensive algorithmic trading courses available online with lecture recordings and lifetime access and support.


Building an algorithmic trading strategy.


From algo trading strategies to paradigms and modeling ideas, I come to that section of the article where I will tell you how to build a basic algorithmic trading strategy.


How do you start with the implementation of algo trading strategies?


That is the first question that must have come to your mind, I presume. The point is that you have already started by knowing the basics and paradigms of algorithmic trading strategies while reading this article. Now, that our bandwagon has it’s engine turned on, it is time to press on the accelerator.


And how exactly is this done?


I will explain how an algorithmic trading strategy is built, step by step. The concise description will give you an idea about the entire process.


The first step is to decide the strategy paradigm. It can be Market Making, Arbitrage based, Alpha generating, Hedging or Execution based strategy. For this particular instance, I will choose pair trading which is a statistical arbitrage strategy that is market neutral (Beta neutral) and generates alpha, i. e.makes money irrespective of market movement.


You can decide on the actual securities you want to trade based on market view or through visual correlation (in the case of pair trading strategy). Establish if the strategy is statistically significant for the selected securities. For instance, in the case of pair trading, check for co-integration of the selected pairs.


Now, code the logic based on which you want to generate buy/sell signals in your strategy. For pair trading check for “mean reversion”; calculate the z-score for the spread of the pair and generate buy/sell signals when you expect it to revert to mean. Decide on the “Stop Loss” and “Profit Taking” conditions.


손실 중지 & # 8211; A stop-loss order limits an investor’s loss on a position in a security. It fires an order to square off the existing long or short position to avoid further losses and helps to take emotion out of trading decisions. 이익을 얻으십시오 & # 8211; take-profit orders are used to automatically close out existing positions in order to lock in profits when there is a move in a favorable direction. Quoting or Hitting strategy.


It is very important to decide if the strategy will be “quoting” or “hitting”. Execution strategy to a great extent decides how aggressive or passive your strategy is going to be.


Quoting – In pair trading you quote for one security and depending on if that position gets filled or not you send out the order for the other. In this case, the probability of getting a fill is lesser but you save bid-ask on one side. Hitting - In this case, you send out simultaneous market orders for both securities. The probability of getting a fill is higher but at the same time slippage is more and you pay bid-ask on both sides.


The choice between the probability of fill and Optimized execution in terms of slippage and timed executive is what this is if I have to put it that way. If you choose to quote, then you need to decide what are quoting for, this is how pair trading works. If you decide to quote for the less liquid security, slippage will be less but the trading volumes will come down liquid securities on the other hand increase the risk of slippage but trading volumes will be high.


Using stats to check causality is another way of arriving at a decision, i. e. change in which security causes change in the other and which one leads. The causality test will determine the “lead-lag” pair; quote for the leading and cover the lagging security.


How do you decide if the strategy you chose was good or bad?


How do you judge your hypothesis?


This is where back-testing the strategy comes as an essential tool for estimation of the performance of the designed hypothesis based on historical data. A strategy can be considered to be good if the backtest results and performance statistics back the hypothesis.


Hence, it is important to choose historical data with a sufficient number of data points. This is to create a sufficient number of sample trades (at least 100+ trades) covering various market scenarios (bullish, bearish etc.). Ensure that you make provision for brokerage and slippage costs as well. This will get you more realistic results but you might still have to make some approximations while backtesting. For instance, while backtesting quoting strategies it is difficult to figure out when you get a fill. So, the common practice is to assume that the positions get filled with the last traded price.


What kind of tools should you go for, while backtesting?


Since backtesting for algorithmic trading strategies involves a huge amount of data, especially if you are going to use tick by tick data. So, you should go for tools which can handle such mammoth load of data.


R or MATLAB?


R is excellent for dealing with huge amounts of data and has a high computation power as well. Thus, making it one of the better tools for backtesting. Also, R is open source and free of cost. We can use MATLAB as well but it comes with a licensing cost.


Fine, I just ripped off Ben Parker’s famous quotation from the Spiderman movie (not the Amazing one). But trust me, it is 100% true. No matter how confident you seem with your strategy or how successful it might turn out previously, you must go down and evaluate each and everything in detail. There are several parameters that you would need to monitor when analyzing a strategy’s performance and risk. Some important metrics/ratios are mentioned below:


Total Returns (CAGR)- Compound Annual Growth Rate (CAGR). It is the mean annual growth rate of an investment over a specified period of time longer than one year. Hit Ratio - Order to trade ratio. Average Profit per Trade - Total profit divided by the total number of trades Average Loss per trade - Total loss divided by the total number of trades Maximum Drawdown – Maximum loss in any trade Volatility of Returns - Standard deviation of the “returns” Sharpe Ratio - Risk adjusted returns, i. e. excess returns (over risk free rate) per unit volatility or total risk.


The entire process of Algorithmic trading strategies does not end here. What I have provided in this article is just the foot of an endless Everest. In order to conquer this, you must be equipped with the right knowledge and mentored by the right guide . That’s where QuantInsti comes in, to guide you through this journey. QuantInsti will help you conquer the Everest at the end. If you want to know more about algorithmic trading strategies then you can click here.

Comments