거래 전략 r
App Store를 통해 가져 오기 우리의 응용 프로그램 에서이 게시물을 읽으십시오!
R : 거래 전략을 역행하십시오. Quantumod와 R. 에 초보자.
나는 R에 매우 익숙하며 WealthLab에서 이미 프로그래밍 한 전략을 다시 테스트하려고합니다.
내가 이해하지 못하는 몇 가지 것들 (그리고 그것은 분명히 작동하지 않습니다 :)
가까운 가격을 멋지게 벡터에 넣지는 않습니다. 또는 어떤 종류의 벡터지만 구조로 시작하고 나는이 함수가 무엇을하는지 정말로 이해하지 못한다. 그게 내 시리즈 [, 1] 호출이 아마 작동하지 않는 이유입니다.
n - nrow (series)도 작동하지 않지만 Loop에 필요합니다.
그래서이 두 가지 질문에 대한 답변을 얻으려면 내 전략이 효과가 있다고 생각합니다. 어떤 도움을 주셔서 감사합니다. R은 다른 언어로 프로그래밍 경험을해도 매우 복잡해 보입니다.
두 번째 질문부터 시작합니다.
따라서 실제 xts 객체에서 작업하려면 get을 사용해야합니다.
귀하의 첫 번째 질문에 대해 - 나는 당신이 정말로 벡터로 데이터를 가져올 필요가 없다고 생각합니다 - xts 객체는 날짜별로 인덱싱 된 배열이며 작업하기 쉽습니다. 그래도 데이터를 얻으려면 사용할 수 있습니다.
이제 전략의 간단한 백 테스트를 시작하려면 다음 단계를 수행하는 것이 좋습니다.
전략을 정의하십시오. 2. 배열을 생성하거나 각 요일의 위치를 나타내는 열을 xts 객체에 추가하십시오. 1은 길고, 0은 위치가 없으며 -1은 짧습니다 (나중에는 레버리지 번호로 게임을 할 수 있습니다). 3. 매일의 수익을 포지션과 곱하면 전략의 리턴 벡터를 얻을 수 있습니다. 4. 결과를 검토하십시오 - 내 추천은 PerformanceAnalytics입니다.
간단한 전략 - SMA20을 닫을 때 구매하십시오.
R을 이용한 양적 거래 전략 : 단계별 가이드.
이 글에서는 R을 사용하여 거래 전략을 수립하는 것에 대해 논의 할 것입니다. R을 사용하여 거래 전문 용어에 머무르기 전에 R이 무엇인지 이해하는 데 시간을 할애해야합니다. R은 오픈 소스입니다. 4000 개가 넘는 애드온 패키지가 있으며, 18000 가지 이상의 LinkedIn 그룹 구성원과 현재 80 개의 R Meetup 그룹이 있습니다. 특히 데이터 분석을위한 통계 분석을위한 완벽한 도구입니다. Comprehensive R Archive Network의 간결한 설정은 CRAN이 필요한 기본 설치와 함께 패키지 목록을 제공함을 알고 있습니다. 분석에 따라 사용할 수있는 패키지가 많이 있습니다. 거래 전략을 구현하기 위해 quantstrat이라는 패키지를 사용합니다.
기본 거래 전략의 4 단계 프로세스.
가설 형성 시험 정제 생산.
우리의 가설은 "시장은 평균 반향이다"라고 공식화되어있다. 평균 회귀 (mean reversion)는 결국 가격이 결국 평균값으로 돌아 간다는 것을 나타내는 이론입니다. 두 번째 단계는 우리 가설에 대한 전략을 공식화하고 지표, 신호 및 성과 지표를 계산하는 가설을 검증하는 것입니다. 테스트 단계는 세 가지 단계, 데이터 가져 오기, 전략 작성 및 출력 분석으로 나눌 수 있습니다. 이 예에서는 NIFTY-Bees를 고려합니다. Goldman Sachs가 관리하는 Exchange 거래 펀드입니다. NSE는 장비에 대한 막대한 양을 가지고 있으므로이를 고려합니다. 아래 이미지는 동일 가격의 Open-High-Low-Close 가격을 보여줍니다.
우리는 가격의 변동을 비교하기위한 기준점을 설정합니다. 가격이 증가하거나 감소하면 임계 값 열을 업데이트합니다. 종가는 상위 밴드와 하위 밴드와 비교됩니다. 상부 밴드가 넘어지면, 그것은 판매를위한 신호입니다. 마찬가지로 낮은 밴드가 넘어지면 팔리는 신호입니다.
코딩 섹션은 다음과 같이 요약 될 수 있습니다.
전략 결과물에 대한 헬리콥터보기가 아래 다이어그램에 나와 있습니다.
따라서 시장이 평균 반전이라는 가설이 뒷받침된다. 이것은 역기능 테스트이므로 평균 수익률과 실현 된 이익을 개선 할 수있는 거래 매개 변수를 조정할 여지가 있습니다. 다른 임계 값 레벨, 보다 엄격한 입력 규칙, 정지 손실 등을 설정하여 수행 할 수 있습니다. 백 테스트를 위해 더 많은 데이터를 선택하고, 임계 값 설정을 위해 Bayseian 접근법을 사용하고, 변동성을 고려합니다.
일단 백 - 테스트 결과에 의해 뒷받침되는 거래 전략에 대해 확신하고 나면 라이브 거래를 시작할 수 있습니다. 프로덕션 환경은 그 자체로 큰 주제이며 기사의 맥락에서 벗어납니다. 간단히 설명하면 거래 플랫폼에 전략을 쓰는 것입니다.
앞서 언급했듯이, 우리는 quantstrat 패키지를 사용하여 모델을 구축 할 것입니다. Quantstrat는 신호 기반 정량 전략을 모델링하고 백 테스트하는 일반 인프라를 제공합니다. 매우 적은 코드 행에서 전략을 빌드하고 테스트 할 수있게 해주는 고급 추상화 계층 (xts, FinancialInstrument, blotter 등을 기반으로 함)입니다.
퀀트 스트릿의 주요 특징은 다음과 같다.
지표, 신호 및 규칙을 포함하는 전략 지원 다중 자산 포트폴리오에 전략 적용 가능 시장, 제한, 중지 및 중지 오더 유형 지원 주문 크기 조정 및 매개 변수 최적화를 지원합니다.
이 게시물에서 우리는 지표, 신호 및 규칙을 포함하는 전략을 수립합니다.
일반적인 신호 기반 모델의 경우 다음 사항을 고려해야합니다.
계측기 - 시장 데이터 포함 지표 - 시장 데이터로부터 도출 된 정량적 가치 신호 - 시장 데이터와 지표 간의 상호 작용 결과 규칙 - 시장 데이터, 지표 및 신호를 사용하여 주문을 생성합니다.
별로 신경 쓰지 않고 코딩 부분을 논의 해 봅시다. 우리는 코딩을 위해 R studio를 선호하며 동일한 것을 사용하라고 주장합니다. 전략을 프로그래밍하기 전에 특정 패키지가 설치되어 있어야합니다.
다음 명령 세트는 필요한 패키지를 설치합니다.
패키지를 설치하면 추가 사용을 위해 패키지를 가져옵니다.
csv 파일에서 데이터를 읽고 xts 객체로 변환합니다.
우리는 주식, 통화, 초기 자본 및 전략 유형으로 포트폴리오를 초기화합니다.
동일한면에서 두 번 이상 교역하려면 위치 제한을 추가하십시오.
전략 개체를 만듭니다.
우리는 거래하고자하는 임계 값을 계산하는 함수를 만듭니다. 가격이 thresh1만큼 이동하면 임계 값을 새 가격으로 업데이트합니다. 거래를위한 새로운 밴드는 Threshold +/- Thresh2입니다. reclass 함수를 사용하지만 출력은 xts 객체입니다.
표시기, 신호 및 거래 규칙을 추가하십시오.
전략을 실행하고 주문서를보십시오.
포트폴리오를 업데이트하고 무역 통계를보십시오.
다음은 완전한 코드입니다.
이러한 기본 사항에 익숙해지면 R에서 quantimod 패키지를 사용하는 방법을 살펴 보거나 C ++을 잘 이해할 수 있도록 C ++로 코딩 된 예제 전략을 살펴보십시오.
자신의 자동 트레이딩 데스크를 시작하려는 소매업 종사자 또는 기술 전문가 인 경우 오늘 알 고 트레이딩을 배우십시오! 자동화 된 거래 아키텍처, 시장 미세 구조, 전략 백 테스트 시스템 및 주문 관리 시스템과 같은 기본 개념으로 시작하십시오.
코멘트는 닫힙니다.
최근 인기있는 글.
가장 많이 방문한 기사.
R 사용자를위한 작업.
bavotasan 디자인을 사용하여 WordPress에 의해 구동됩니다.
저작권 및 사본; 2017 R-bloggers. 판권 소유. 이 웹 사이트의 이용 약관.
R 상인.
Quantitative Finance에서 R 및 관련 도구 사용
R에서 시계열 데이터 시각화
R에서 Time Series Data 시각화에 대한 DataCamp 과정을 발표하게되어 매우 기쁩니다. 이 과정은 R 스킬 트랙이있는 Time Series의 일부이기도합니다. 자유롭게 봐, 첫 번째 챕터는 무료입니다!
코스 설명.
속담처럼, "차트는 천 단어의 가치가있다". 이것이 시각화가 데이터를 더 잘 이해할 수있는 가장 유용하고 강력한 방법 인 이유입니다. 이 과정을 거친 후에 R 시계열 시각화 기능에 대한 매우 훌륭한 개요를 얻을 수 있으며 이후 분석을 위해 선택할 모델을 더 잘 결정할 수 있습니다. 당신은 또한 전달하고자하는 메시지를 효율적이고 아름다운 방법으로 전달할 수 있습니다.
강의 개요.
1 장 : R 시계열 시각화 도구.
이 장에서는 기본적인 R 시계열 시각화 도구를 소개합니다.
2 장 : 단 변량 시계열.
단 변량 플롯은 가능하면 데이터의 분포, 중심 경향 및 확산에 대해 가능한 많이 배우도록 설계되었습니다. 이 장에서는 단 변량 시계열을 진단하는 데 사용되는 몇 가지 시각 도구를 제공합니다.
3 장 : 다 변수 시계열.
다 변수 시계열을 다뤄야한다면 어떻게해야합니까? 이 장에서는 분포, 중심 경향 및 쌍 또는 데이터 그룹에 퍼져있는 패턴을 식별하는 방법을 학습합니다.
4 장 : 사례 연구 : 기존 포트폴리오를 개선하는 주식을 시각적으로 선택합니다.
지금까지 배운 모든 것을 실제로 연습 해 봅시다! 이미 주식 포트폴리오를 가지고 있다고 가정하고 투자 할 여분의 현금이 있다면 어떻게하면 현물로 새로운 주식을 선택하여 추가 현금을 투자 할 수 있습니까? 개별 주식의 통계적 특성을 기존 포트폴리오와 비교하여 분석하면 문제를 해결할 수 있습니다.
R을 IQFeed에 QuantTools 패키지로 연결.
IQFeed는 농업, 에너지 및 금융 시장을 포괄하는 스트리밍 데이터 서비스 및 거래 솔루션을 제공합니다. 소매 사용자 및 소규모 기관을 대상으로하는 잘 알려진 데이터 공급 업체입니다. 구독료는 약 $ 80 / 월부터 시작됩니다.
Stanislav Kovalevsky는 QuantTools라는 패키지를 개발했습니다. 양적 거래 모델링을 향상시키기 위해 설계된 일체형 패키지입니다. Yahoo, Google, Finam, MOEX 및 IQFeed와 같은 여러 소스에서 과거 시장 데이터를 다운로드하고 구성 할 수 있습니다. 가장 관심을 끄는 기능은 IQFeed를 R에 연결하는 기능입니다. 저는 몇 년 동안 IQFeed를 사용해 왔으며 이에 만족합니다 (저는 어떤 회사에서도 회사와 아무 관계가 없습니다). 방법). 자세한 내용은 여기를 참조하십시오. 나는 잠시 동안 R 내에서 통합을 찾고 있었지만 여기에 있습니다. 결과적으로 몇 가지 테스트를 마친 후에도 Python에 있던 코드를 R로 옮겼습니다. 완성을 위해 여기에 Python을 사용하여 IQFeed에서 기록 데이터를 다운로드하는 방법을 설명하는 링크를 제공합니다.
QuantTools는 네 가지 주요 기능을 제공합니다 : 시장 데이터 입수, 시장 데이터 저장 / 회수, 시계열 데이터 플롯 및 백 테스트.
먼저 IQfeed가 열려 있는지 확인하십시오. 매일 또는 일중 데이터를 다운로드 할 수 있습니다. 아래 코드는 2017 년 1 월 1 일부터 2017 년 6 월 1 일까지 SPY의 일일 가격 (개방, 고가, 저가, 마감)을 다운로드합니다.
아래 코드는 2017 년 5 월 1 일부터 2017 년 5 월 3 일 사이의 데이터를 다운로드합니다.
period 매개 변수에 유의하십시오. 틱, 1 분, 5 분, 10 분, 15 분, 30 분, 시간, 일, 주, 월 중 원하는 값을 취할 수 있습니다.
QuantTools는 진드기 마켓 데이터를 쉽게 관리하고 저장하는 프로세스를 만듭니다. 스토리지 매개 변수를 설정하기 만하면 바로 사용할 수 있습니다. 매개 변수는 저장하려는 날짜와 기호가있는 곳입니다. 더 많은 기호를 추가 할 수 있고 언제든지 저장 장치에 표시되지 않으면 QuantTools는 지정된 시작 날짜부터 데이터를 가져 오려고합니다. 아래 코드는 C : / Users / Arnaud / Documents / Market Data / iqfeed 디렉토리에 데이터를 저장합니다. 계측기별로 하나의 하위 폴더가 있으며 데이터는. rds 파일로 제공됩니다.
특정 날짜 사이에 데이터를 저장할 수도 있습니다. 위 코드의 마지막 줄을 다음 중 하나로 바꾸십시오.
이제 저장된 데이터 중 일부를 되돌리고 싶다면 다음과 같이 실행하십시오.
진드기 만 로컬 저장소에서 지원되므로 기간은 & # 8216; tick & # 8217;이어야합니다.
QuantTools는 주말, 공휴일 및 야간 간격없이 시계열 데이터를 플로팅하는 plot_ts 함수를 제공합니다. 아래 예제에서 나는 먼저 위에 저장된 데이터를 검색 한 다음 처음 100 개의 가격 관측을 선택하고 마지막으로 차트를 그립니다.
두 가지주의 사항 : 첫 번째 스파이는 data. table 객체이므로 위의 구문을 사용하십시오. data. table 기능에 대한 간략한 개요를 보려면 DataCamp의 우수한 치트 시트를 살펴보십시오. 두 번째로 로컬 매개 변수는 데이터가 내부 저장소에서 검색 될 때 TRUE입니다.
QuantTools는 C ++ API를 사용하여 자신의 거래 전략을 작성할 수 있습니다. 기본적으로 C ++ 코드이므로이 부분을 자세히 설명하지 않을 것입니다. QuantTools 웹 사이트의 예제 섹션을 참조하십시오.
전반적으로이 패키지는 매우 유용하고 잘 문서화되어 있습니다. 누락 된 유일한 비트는 R과 IQFeed 사이의 라이브 피드로 실제 솔루션을 최종 솔루션으로 만듭니다.
평소처럼 모든 의견 환영합니다.
BERT : R Excel 연결의 신참입니다.
몇 달 전에 독자가 R과 Excel을 연결하는 새로운 방식을 알려줍니다. 나는이 문제가 얼마나 오랫동안 지속되었는지 알지 못한다. 그러나 나는 그것에 대해 전혀 알지 못했으며 블로그 게시물이나 기사를 보지 못했다. 그래서 도구가 실제로 가치가있는 것처럼 게시물을 쓰기로 결정했는데 누군가가 묻기 전에는 어떤 방식 으로든 회사와 관련이 없습니다.
BERT는 기본 Excel R Toolkit의 약자입니다. 무료 (GPL v2에 따라 라이선스가 있음)이며 Structured Data LLC에서 개발했습니다. 현재 BERT의 최신 버전은 1.07입니다. 자세한 내용은 여기를 참조하십시오. 보다 기술적 인 관점에서 볼 때 BERT는 Excel 스프레드 시트 셀에서 R 함수를 실행할 수 있도록 설계되었습니다. Excel 용어로, R에 사용자 정의 함수 (UDF)를 작성했습니다.
이 게시물에서 저는 R과 Excel이 BERT를 통해 어떻게 상호 작용하는지 보여주지 않을 것입니다. 여기, 여기, 여기 아주 좋은 자습서가 있습니다. 대신 BERT를 사용하여 제어 타워를 구축하는 방법을 보여 드리고자합니다. 내 거래를 위해서.
내 거래 신호는 긴 R 파일 목록을 사용하여 생성되지만 결과를 빠르고 효율적으로 표시하려면 Excel의 유연성이 필요합니다. 위에서 볼 수 있듯이 BERT는 나를 위해이 작업을 수행 할 수 있지만 필요에 맞게 응용 프로그램을 조정하고 싶습니다. XML, VBA, R 및 BERT의 기능을 결합하여 VBA 코드가 최소 인 Excel 파일 형태로 멋지면서도 강력한 응용 프로그램을 만들 수 있습니다. 궁극적으로 데이터베이스 관리, 신호 생성, 주문 제출 등 내 포트폴리오를 관리하는 데 필요한 모든 작업을 수집하는 단일 Excel 파일이 있습니다. 내 접근법은 아래의 세 단계로 세분화 될 수 있습니다.
XML을 사용하여 사용자 정의 메뉴 및 단추를 Excel 파일로 작성하십시오. 위의 메뉴와 버튼은 기본적으로 VBA 함수를 호출합니다. 이러한 VBA 함수는 BERT를 사용하여 정의 된 R 함수를 포괄합니다.
이 접근법을 통해 R, SQL 및 Python에 보관 된 코드의 핵심과 Excel, VBA & amp; XML. 다음 섹션에서는 이러한 접근 방식을 개발하기위한 전제 조건과 최소한의 VBA 코드로 R에서 Excel로 데이터를 단순히 전달하는 데 BERT가 어떻게 사용될 수 있는지 설명하는 단계별 가이드를 제시합니다.
1 & # 8211; 이 링크에서 BERT를 다운로드하여 설치하십시오. 설치가 완료되면 아래와 같이 단추가있는 Excel에 새 추가 기능 메뉴가 있어야합니다. 이것이 BERT가 Excel에서 구체화 된 방법입니다.
2 & # 8211; 사용자 지정 UI 편집기 다운로드 및 설치 : 사용자 지정 UI 편집기를 사용하면 Excel 리본에서 사용자 정의 메뉴 및 단추를 만들 수 있습니다. 단계별 절차가 여기에서 사용할 수 있습니다.
1 & # 8211; R 코드 : 아래의 R 함수는 설명의 목적으로 만 사용되는 매우 간단한 코드입니다. 선형 회귀 분석에서 잔차를 계산하여 반환합니다. 이것은 우리가 Excel에서 검색하고자하는 것입니다. 원하는 디렉토리에 myRCode. R이라는 파일 (다른 이름은 괜찮습니다)에 저장하십시오.
2 & # 8211; BERT의 function. R : Excel에서 Add-Ins - & gt; 홈 디렉토리를 열고 functions. R이라는 파일을 엽니 다. 이 파일에 다음 코드를 붙여 넣으십시오. 올바른 경로를 삽입했는지 확인하십시오.
이것은 위에서 만든 R 파일을 BERT로 가져 오는 것입니다. 그런 다음 파일 functions. R을 저장하고 닫습니다. 1 단계에서 만든 R 파일을 변경하려면 BERT 버튼 & # 8220; 시작 파일 다시로드 & # 8221;를 사용하여 다시로드해야합니다. Excel의 추가 기능 메뉴에서.
3 & # 8211; Excel에서 : myFile. xslm이라는 파일을 만들고 저장하십시오 (다른 이름은 상관 없습니다). 이 파일은 원하는 디렉토리에 저장 한 매크로 사용 가능 파일입니다. 파일이 저장되면 닫습니다.
4 & # 8211; 위에서 만든 파일을 사용자 정의 UI 편집기에서 엽니 다. 파일이 열리면 아래 코드를 붙여 넣습니다.
XML 편집기에서 다음과 같은 내용을 가져야합니다.
본질적으로이 XML 코드는 Excel 리본에 추가 메뉴 (RTrader), 새 그룹 (My Group) 및 사용자 정의 단추 (New Button)를 만듭니다. 일단 끝나면 Excel에서 myFile. xslm을 열고 사용자 정의 UI 편집기를 닫습니다. 너는 이와 비슷한 것을보아야한다.
5 & # 8211; VBA 편집기 열기 : myFile. xlsm에서 새 모듈을 삽입하십시오. 아래 코드를 새로 만든 모듈에 붙여 넣으십시오.
그러면 새로운 결과를 처리하기 전에 워크 시트의 이전 결과가 지워집니다.
6 & # 8211; 새 버튼 클릭 : 이제 스프레드 시트로 돌아가서 RTrader 메뉴에서 & # 8220; 새 버튼 & # 8221;을 클릭하십시오. 단추. 아래에 보이는 것과 같은 것이 보일 것입니다.
위의 가이드는 BERT를 사용하여 달성 할 수있는 것의 매우 기본적인 버전이지만 여러 가지 특정 도구의 기능을 결합하여 사용자 지정 응용 프로그램을 빌드하는 방법을 보여줍니다. 필자의 관점에서 볼 때 이러한 접근법에 대한 관심은 R과 Excel을 분명하게 결합 할 수있을뿐만 아니라 Python, SQL 등의 XML 코드 (및 일괄 처리)를 통해 포함 할 수 있다는 점입니다. 이것은 내가 필요한 것입니다. 마지막으로 BERT에 대한 경험이있는 사람이 있는지 궁금 할 것입니다.
거래 전략 : 샘플 데이터를 최대한 활용합니다.
거래 전략을 테스트 할 때 공통적 인 접근 방식은 초기 데이터 세트를 샘플 데이터로 나누는 것입니다 : 모델의 교정을 위해 설계된 데이터 부분과 샘플 데이터가 부족한 경우 : 캘리브레이션을 검증하고 성능을 보장하기 위해 사용되는 데이터 부분 샘플에서 생성 된 내용은 실제 세계에 반영됩니다. 일반적으로 초기 데이터의 약 70 %는 교정 (즉, 샘플)에 사용되며 30 %는 유효성 검사 (즉, 샘플 외)에 사용될 수 있습니다. 그런 다음 샘플 데이터의 내부 및 외부를 비교하면 모델이 충분히 견고한 지 여부를 결정하는 데 도움이됩니다. 이 게시물은 한 단계 더 나아가는 것을 목표로하고 샘플 데이터가 샘플에서 생성 된 것과 일치하는지 여부를 결정하는 통계적 방법을 제공합니다.
아래의 차트에서 파란색 영역은 내 전략 중 하나에 대한 샘플 성능이 좋지 않음을 나타냅니다.
간단한 육안 검사는 샘플 성능의 안팎에서 좋은 적합성을 보여 주지만이 정도의 확신은 어느 정도입니까? 이 단계에서는 별다른 문제가 아닙니다. 진정으로 필요한 것은 샘플 데이터 세트 안팎의 유사성을 측정하는 것입니다. 통계적으로 보면 이는 동일한 분포에서 나오는 표본 성과 수치에 대한 가능성으로 해석 될 수 있습니다. Kruskall-Wallis Test와 정확히 같은 비모수 통계 테스트가 있습니다. 이 테스트의 좋은 정의는 R-Tutor에서 찾을 수 있습니다. 데이터 샘플 모음은 관련없는 모집단에서 왔고 샘플이 서로 영향을주지 않으면 독립적입니다. Kruskal-Wallis Test를 사용하여 인구 분포가 정규 분포를 따르는 것으로 가정하지 않고 동일한지 여부를 결정할 수 있습니다. & # 8221; 이 테스트의 추가 이점은 정규 분포를 가정하지 않는 것입니다.
이 프레임 워크에 들어 맞는 동일한 특성의 다른 테스트가 있습니다. Mann-Whitney-Wilcoxon 테스트 또는 Kolmogorov-Smirnov 테스트는 여기에 설명 된 프레임 워크에 완벽하게 어울립니다. 그러나이 문서에서는이 테스트의 장단점에 대해 논의하지 않습니다. R 예제와 함께 좋은 설명을 여기서 찾을 수 있습니다.
위 차트와 분석을 생성하는 데 사용 된 코드는 다음과 같습니다.
위의 예에서 샘플 기간은 샘플 기간 외보다 길으므로 임의로 샘플 데이터의 1000 개 하위 집합을 생성했으며 각 하위 집합은 샘플 데이터가없는 부분과 길이가 같습니다. 그런 다음 샘플 하위 집합에 대해 각각 샘플 하위 집합에 대해 테스트하고 p 값을 기록했습니다. 이 프로세스는 Kruskall-Wallis 테스트에 대한 단일 p 값을 생성하지 않고 분석을보다 강력하게 해주는 분포를 생성합니다. 이 예에서 p - 값의 평균은 영가설이 받아 들여 져야 함을 나타내는 영 (0.478)보다 훨씬 높습니다. 샘플 데이터의 안팎이 동일한 분포에서 나온다는 강력한 증거가 있습니다.
평소처럼이 포스트에서 제시된 것은 문제의 표면을 긁어 내고 개인의 필요에 맞춰야 만하는 장난감의 예입니다. 그러나 나는 그것이 샘플 결과를 평가하는 흥미롭고 합리적인 통계 틀을 제안한다고 생각한다.
이 게시물은 다음 두 개의 논문에서 영감을 얻었습니다.
Vigier Alexandre, Chmil Swann (2007), "유전 적 진화 무역 전략의 표본 성능에 대한 다양한 최적화 기능의 영향", 금융 시장 전망 예측.
Vigier Alexandre, Chmil Swann (2010),«샘플 일관성의 개선 / 개선을위한 최적화 프로세스, 주식 시장 사례», JP Morgan Cazenove Equity Quantitative Conference, 런던 2010 년 10 월.
fidlr 소개 : Fiscal 데이터 LoadeR.
fidlr은 다양한 공급자로부터 재무 데이터 다운로드 프로세스를 단순화하도록 설계된 RStudio 애드 인입니다. 이 초기 버전은 quantmod 패키지의 getSymbols 함수에 대한 래퍼이며 Yahoo, Google, FRED 및 Oanda 만 지원됩니다. 아마도 시간이 지남에 따라 기능을 추가 할 것입니다. 평상시와 같이, 일종의 알림으로 : 소프트웨어는 어떠한 보증도하지 않고 & # 8221; & # 8221; & # 8221; & # 8221;
fidlr을 설치하고 사용하는 방법은 무엇입니까?
여기 Github 저장소에서 addin / package를 얻을 수 있습니다 (나중에 CRAN에 등록 할 것입니다). addin을 설치하십시오. RStudio Addins를 설치하는 훌륭한 튜토리얼이 있습니다. addin이 설치되면 Addin 메뉴에 나타나야합니다. 메뉴에서 fidlr을 선택하면 아래 그림과 같은 창이 나타납니다. 소스 드롭 다운 메뉴에서 데이터 제공 업체를 선택하십시오. 날짜 메뉴에서 날짜 범위 선택 도구 텍스트 상자에 다운로드하려는 기호를 입력하십시오. 여러 기호를 다운로드하려면 기호를 쉼표로 구분하여 입력하십시오. 라디오 버튼을 사용하여 CSV 파일 또는 글로벌 환경에서 악기를 다운로드할지 여부를 선택하십시오. csv 파일은 작업 디렉토리에 저장되며 악기 당 하나의 csv 파일이 있습니다. Run을 눌러 데이터를 가져 오거나 Close를 클릭하여 추가 기능을 닫습니다.
오류 메시지 및 경고는 기본 패키지 (quantmod 및 Shiny)가 처리하며 콘솔에서 읽을 수 있습니다.
이것은 프로젝트의 첫 번째 버전이므로 완벽을 기대하지는 않지만 잘하면 시간이 지남에 따라 개선 될 것입니다. 의견, 제안, 버그 등을 알려주십시오. & # 8230; tortradergmail.
R에서 가격 파일 데이터베이스 유지 보수.
양적 연구를하는 것은 많은 데이터 처리를 의미하며이를 달성하기 위해서는 깨끗하고 신뢰할 수있는 데이터가 필요합니다. 정말로 필요한 것은 (인터넷 연결 없이도) 쉽게 접근 할 수있는 깨끗한 데이터입니다. 가장 효율적인 방법은 CSV 파일 세트를 유지하는 것입니다. 분명히이 프로세스는 여러 가지 방법으로 처리 될 수 있지만 CSV 파일을 저장하고 업데이트하는 디렉토리를 유지 관리하는 데는 매우 효율적이고 간단한 초과 근무 시간이 필요했습니다. 저는 장비 당 하나의 CSV 파일을 가지고 있으며 각 파일은 그것이 들어있는 도구의 이름을 따서 붙여졌습니다. 내가 그렇게하는 이유는 두 가지입니다. 첫째, Yahoo, Google 등의 데이터를 다운로드 (가격)하고 싶지 않습니다. & # 8230; 새로운 아이디어를 테스트하고 싶을 때마다 문제를 확인하고 수정 한 후에는 다음 번에 동일한 도구가 필요할 때 다시해야한다고 생각합니다. 단순하지만 매우 효율적입니다. 프로세스는 아래 차트에 요약되어 있습니다.
다음에 나오는 모든 내용에서 야후의 데이터가 온다고 가정합니다. 코드는 Google, Quandl 등의 데이터에 맞게 수정해야합니다. & # 8230; 또한 일일 가격 데이터를 업데이트하는 과정을 제시합니다. 설정은 높은 빈도 데이터 및 다른 유형의 데이터 집합 (즉, 가격과 다를 경우)에 따라 다릅니다.
1 & # 8211; 초기 데이터 다운로드 (listOfInstruments. R & historicalData. R)
listOfInstruments. R 파일은, 모든 인스트르먼트의리스트만을 포함한 파일입니다.
악기가 내 목록의 일부가 아닌 경우 (즉, 내 데이터 폴더에 CSV 파일이없는 경우) 처음 사용하는 경우 초기 기록 데이터 세트를 다운로드해야합니다. 아래의 예는 Yahoo Finance에서 일간 ETFs 일일 가격을 2000 년 1 월로 다운로드하여 csv 파일에 저장합니다.
2 & # 8211; 기존 데이터 업데이트 (updateData. R)
아래 코드는 전용 폴더의 기존 파일에서 시작하여 모든 파일을 차례로 업데이트합니다. 나는 휴일을 제외하고는 보통 매일이 과정을 운영합니다. 새 악기를 추가하려면 위의 1 단계 만 실행하면됩니다.
3 & # 8211; 배치 파일 만들기 (updateDailyPrices. bat)
작업의 또 다른 중요한 부분은 위의 업데이트 프로세스를 자동화하는 배치 파일을 만드는 것입니다 (필자는 Windows 사용자 임). 이렇게하면 R / RStudio를 열고 거기에서 코드를 실행할 수 있습니다. 아래의 코드는. bat 파일에 있습니다 (경로는 독자의 설정으로 수정해야합니다). 실행을 추적하기 위해 출력 파일 (updateLog. txt)을 추가했습니다.
위의 프로세스는 일별 가격 데이터를 업데이트하는 방법 만 설명하기 때문에 매우 간단합니다. 나는 이것을 잠시 동안 사용 해왔고, 지금까지 나를 위해 매우 원활하게 작업 해왔다. 고급 데이터 및 / 또는 높은 주파수의 경우 상황이 훨씬 더 까다로워 질 수 있습니다.
평소처럼 모든 의견 환영합니다.
로봇의 부상 (고문 & # 8230;)
자산 관리 산업은 큰 변화를 겪고 있습니다. 지난 2 년 동안 RA (Robots Advisors)가 새로운 선수로 등장했습니다. 용어 자체는 다양한 서비스를 포괄하므로 정의하기 어렵습니다. 일부는 전통적인 고문이 고객의 돈을 더 효율적으로 배분할 수 있도록 돕기 위해 고안되었으며 일부는 실제 블랙 박스입니다. 사용자는 몇 가지 기준 (연령, 소득, 어린이 등)을 입력하면 로봇이 맞춤형 할당을 제안합니다. 이 두 극단 사이에는 다양한 제안이 있습니다. Wikipedia의 정의가 꽤 좋은 것으로 나타났습니다. 그들은 최소한의 인간 개입으로 포트폴리오 관리를 온라인으로 제공하는 재정적 자문단입니다. & # 8221; 보다 정확하게 그들은 알고리듬 기반의 포트폴리오 관리를 사용하여 전통적인 어드바이저가 제공 할 수있는 다양한 서비스를 제공합니다 : 배당 재투자, 컴플 라 이언 스 보고서, 포트폴리오 재조정, 세금 손실 추수 등. (물론 이것은 양적인 투자 공동체가 수십 년 동안 해왔 던 것입니다!). 업계는 아직 초기 단계에 머물러있어 대부분의 선수들이 여전히 소량의 돈을 관리하고 있지만 며칠 전 NYC에있을 때 얼마나 큰 변화가 있었는지 깨달았습니다. RA가 TV에 추가하거나 NYC 택시 지붕에 이름을 올리면 큰 일이 벌어지고 있음을 알게됩니다. & # 8230;
그것은 미디어로부터 점점 더 주목을 받고 있으며 무엇보다 투자자 관점에서 많은 의미를 갖습니다. RA 사용에는 실제로 두 가지 주요 이점이 있습니다.
전통적인 어드바이저에 비해 훨씬 저렴한 수수료 투자가 더 투명하고 단순 해지면서 재무 지식이 제한된 사람들에게 더 매력적입니다.
이 게시물에서 R은 자산 관리 업계의 주요 트렌드가 무엇인지 잘 설명하는 변명 일뿐입니다. 아래 차트는 2014 년 말 현재 가장 많이 사용되는 RA의 시장 점유율을 보여줍니다. 아래 차트를 생성하는 데 사용 된 코드는이 게시물의 끝에 있으며 데이터는 여기에 있습니다.
이 수치는이 업계가 얼마나 빨리 진화했는지에 따라 약간 날짜가 정해지지 만 여전히 매우 유익합니다. 당연히 시장은 Wealthfront and Betterment와 같은 미국의 공급자에 의해 주도되고 있지만 아시아 (8Now!), 스위스 (InvestGlass), 프랑스 (Marie Quantier) & # 8230; 전통적인 자산 관리자가 비즈니스를하는 방식. 저명한 예로는 Fidelity와 Betterment 간의 파트너십이 있습니다. 2014 년 12 월 이후로 20 억 달러 (AUM)를 넘어 섰다.
위의 모든 내용에도 불구하고 실제 변화가 우리보다 앞서 있다고 생각합니다. 그들은 중개인과 중개 수수료가 낮은 제품 (예 : ETF)을 사용하기 때문에 기존 고문보다 훨씬 저렴한 수수료를 부과합니다. RA는 분명히 상당한 시장 점유율을 확보 할 것이지만, 또한 업계 전체가 부과하는 수수료를 낮출 것입니다. 궁극적으로 그것은 전통적인 투자 회사가 사업을하는 방식에 영향을 미칠 것입니다. 몇 년 동안 힘든 시간을 보내고있는 액티브 포트폴리오 관리는 이제 더 많은 어려움을 겪을 것입니다. 비용을 청구하는 높은 수수료는 스스로 재발 명하지 않는 한 정당화하기가 더 어려울 것입니다. 또 하나의 잠재적 영향은 일반적으로 ETF 및 저 수수료 금융 상품의 등장입니다. 분명히 이것은 얼마 전부터 시작되었지만 그 효과가 앞으로 더욱 두드러 질 것이라고 생각합니다. 새로운 세대의 ETF는보다 복잡한 지표와 맞춤형 전략을 추적합니다. 이러한 추세는 필연적으로 강해질 것입니다.
평소처럼 모든 의견 환영합니다.
R 재정 시간 시리즈 팁 모두에 대해 알아야 할 것입니다.
웹상에 떠있는 많은 R 시간 시리즈 자습서가 있습니다. 이 게시물은 그 중 하나가되도록 고안되지 않았습니다. 대신 R에서 재정적 인 시계열을 다루었을 때 가장 유용한 트릭 목록을 소개하고자합니다. 여기에 제시된 기능 중 일부는 매우 강력하지만 유감스럽게도 문서에 묻혀 있으므로 전용 게시물을 작성하고자합니다. 나는 매일 또는 낮은 빈도 계열에 대해서만 연설한다. 빈도가 높은 데이터를 처리하려면 특정 도구가 필요합니다. data. table 또는 highfrequency 패키지가 그 중 일부입니다.
xts : xts 패키지는 R 시리즈의 시계열에 있어야합니다. 아래의 예제는 패키지를로드하고 normaly 분산 리턴의 일별 시계열을 작성합니다.
merge. xts (package xts) : 길이가 같은지 여부에 관계없이 둘 이상의 시리즈를 함께 바인딩 할 때 엄청나게 강력합니다. join 인수는 마술을합니다! 바인딩이 수행되는 방법을 결정합니다.
apply. yearly / apply. monthly (package xts) : 지정된 함수를 주어진 시계열 객체의 각기 다른 기간에 적용합니다. 아래 예제는 tsInter 객체에서 두 번째 시리즈의 월별 및 연간 수익을 계산합니다. 참고 : 나는 합계를 사용한다.
끝점 (패키지 xts) : on으로 지정된 기간에 주어진 마지막 관측치에 해당하는 주어진 xts 객체의 인덱스 값을 추출합니다. 이 예제에서는 끝점을 사용하여 날짜를 선택하는 tsInter 객체의 각 시리즈에 대한 월 최종 날짜를 반환합니다.
na. locf (package zoo) : 각 NA를 그 이전에 가장 최근의 NA로 바꾸는 일반 기능. 몇 개의 구멍이있는 시계열을 다룰 때 매우 유용합니다. 이 시계열이 NA로 인수를 허용하지 않는 R 함수의 입력으로 사용되는 경우 이 예에서는 임의의 가격의 시계열을 만든 다음 인위적으로 그것에 몇 가지 NA를 포함시키고 가장 최근의 값으로 대체합니다.
charts. PerformanceSummary (package PerformanceAnalytics) : 수익률 세트에 대해 자산 지수 차트, 기간별 실적에 대한 막대 및 드래그 다운에 대한 수중 차트를 만듭니다. 이것은 거래 전략의 신속한 육안 검사를 위해 모든 관련 정보를 단일 창에 표시하므로 매우 유용합니다. 아래 예제는 가격 시리즈를 xts 오브젝트로 변환 한 다음 위에서 설명한 3 개의 차트가있는 창을 표시합니다.
위의 목록은 모든 것을 망라한 것은 아니지만 일단이 게시물에서 설명하는 기능을 습득하면 재정적 인 시계열 조작이 훨씬 쉬우 며 코드가 짧아지고 코드 가독성이 향상됩니다.
평소처럼 모든 의견 환영합니다.
양적 포트폴리오 관리의 요인 평가.
주식 포트폴리오와 벤치 마크를 관리 할 때 문제는 절대 수익 전략을 정의하는 것과 매우 다릅니다. 이전의 경우에는 기회가 충분하지 않은 경우 주식을 보유 할 수없는 곳보다 더 많은 주식을 보유해야합니다. 그 이유는 추적 오류 때문입니다. 이것은 포트폴리오 수익의 표준 편차에서 벤치 마크 수익을 뺀 값으로 정의됩니다. 벤치 마크와 비교하여 주식이 적게 들고 추적 오류가 높아질수록 위험도가 높아집니다.
다음의 분석은 주로 액티브 포트폴리오 관리 (Active Portfolio Management)의 책에서 영감을 얻었습니다. Grinold & amp; 칸. 이것은 벤치 마크를 기준으로 포트폴리오를 운영하는 데 관심이있는 사람을위한 성경책입니다. 나는이 주제에 관심이있는 누구나 처음부터 끝까지 책을 읽도록 강력히 권합니다. 그것은 잘 쓰여지고 체계적인 능동적 인 포트폴리오 관리의 토대를 둡니다 (저는 편집인이나 저자에게 아무런 관련이 없습니다).
여기서 우리는 투자 수익을 가능한 한 정확하게 계량화하려고 노력하고 있습니다. 많은 사람들이 여러 가지 도구를 생각해 냈으며이를 달성하기 위해 수많은 도구가 개발되었습니다. 이 포스트에서는 정보 계수 (IC)와 퀀텀 리턴 (QR)이라는 두 가지 간단하고 널리 사용되는 메트릭에 중점을 둡니다.
이 IC는 요인 예측 능력에 대한 개요를 제공합니다. 좀 더 정확히 말하자면, 이것은 요인이 순 수익률 기준으로 주식을 얼마나 잘 평가했는지를 측정 한 것입니다. IC는 메트릭 (예 : 요소)과 순방향 수익 사이의 순위 상관 관계 (ρ)로 정의됩니다. 통계적 측면에서 순위 상관 관계는 두 변수 사이의 종속성에 대한 비모수적인 척도입니다. 크기 n의 샘플에 대해, n 개의 원시 스코어는 랭크로 변환되고, ρ는 다음으로부터 계산됩니다.
순방향 수익의 지평선은 분석가가 정의해야하며 전략의 회전율과 알파 붕괴의 기능입니다 (광범위한 연구 주제였습니다). 분명히 IC는 가능한 한 절대적으로 높아야합니다.
예리한 독자를 위해, Grinold & amp; Kahn은 Information Ratio (IR)와 IC를 연결하는 수식을 제공합니다 : 폭은 독립 베팅 (거래)의 수입니다. 이 수식은 능동적 관리의 기본법으로 알려져 있습니다. 문제는 종종 폭을 정확하게 정의하는 것이 쉽지 않다는 것입니다.
요인 예측치의보다 정확한 추정을하기 위해서는 더 나아가 단계별로 나아가고 요인 값의 분위수를 그룹화하는 것이 필요하다. 그런 다음 각 요소의 평균 순 수익률 (또는 기타 중심 경향 메트릭)을 분석한다. quantiles. 이 도구의 유용성은 간단합니다. 요인은 좋은 IC를 가질 수 있지만 예측력은 소수의 주식에만 국한 될 수 있습니다. 포트폴리오 관리자가 추적 오류 제한을 충족시키기 위해 전체 우주에서 주식을 선택해야하므로 좋지 않습니다. 좋은 분위수 수익률은 개별 분위수와 순 수익률 간의 단조로운 관계로 특징 지워집니다.
S & amp; P500 지수의 모든 주식 (서면 작성 당시). 분명히 생존 선박에 편향이있다. 지수의 주식 목록은 샘플 기간의 시작과 끝 사이에 크게 변경되었지만 설명 목적으로 만 충분하다.
아래의 코드는 S & P500에서 2005 년 1 월부터 오늘까지 개별 주가를 다운로드하고 (다소 시간이 걸립니다) 지난 12 개월 및 지난 달 동안의 원가를 수익으로 전환합니다. 전자는 우리의 요소이며, 후자는 전방 반환 수단으로 사용됩니다.
아래는 정보 계수 및 수량 반환을 계산하는 코드입니다. 이 예제에서는 5 분위수를 사용했지만 다른 그룹화 방법 (terciles, deciles 등)을 사용할 수 있습니다. 샘플 크기, 캡처하고자하는 대상 및 배포 테일에 대한 전반적인 개요 또는 초점을 원하는 경우에 따라 달라집니다. 각 5 분위 내에서의 수익을 산정하기 위해, 중앙값은 중심 경향 추정 자로 사용되었다. 이 측정 값은 산술 평균보다 특이 값에 훨씬 덜 민감합니다.
마지막으로 Quantiles Return 차트를 생성하는 코드입니다.
3 & # 8211; 위의 정보를 이용하는 방법은 무엇입니까?
상기 차트에서 Q1은 12 개월 후 가장 낮았고 Q5는 가장 높았습니다. Q1과 Q5 사이의 분위수 수익은 거의 단조롭게 증가하여 Q5로 떨어지는 주가가 Q1에 떨어지는 주가가 매월 약 1 % 씩 뛰어나다는 것을 분명하게 나타냅니다. 이는 단순한 요소에 대해 매우 중요하고 강력합니다 (실제로 놀랍지는 않습니다.). 따라서 Q5에 해당하는 주식의 비중 확대와 벤치 마크 대비 Q1에 대한 비중 축소를 통해 지수를 상향 조정할 가능성이 더 높다.
0.0206의 IC는 그 자체로 많은 것을 의미하지는 않지만 0과 크게 다르며 지난 12 개월 동안 좋은 예측력을 나타냅니다. 공식적인 중요성 테스트는 평가할 수 있지만이 내용은이 기사의 범위를 벗어납니다.
위의 프레임 워크는 투자 요소의 품질을 평가하는 데 탁월하지만 실생활 구현을 위해 해결해야 할 실제적인 한계가 많습니다.
리 밸런싱 (Rebalancing) : 위의 설명에서 매월 말에 포트폴리오는 완전히 균형을 맞춘 것으로 가정합니다. 이는 Q1에 속하는 모든 주식이 비중 축소이고 Q5에 속하는 모든 주식이 벤치 마크 대비 과체중이라는 것을 의미합니다. 실용적인 이유 때문에 항상 가능한 것은 아닙니다. 일부 주식은 투자 영역에서 제외 될 수 있으며, 산업 또는 업종의 체중에 제약이 있고, 회전율 등에 제약이 있습니다. & # 8230; 거래 비용 : 이것은 위의 분석에서 고려되지 않았으며 이는 실제 구현에 심각한 장애가됩니다. 회전율 고려 사항은 일반적으로 요소 품질에 대한 불이익의 형태로 실생활에서 구현됩니다. 이양률 : 능동적 인 경영의 기본법을 확장 한 것으로 Grinold의 모델 가정은 관리자가 투자 통찰력을 포트폴리오 베팅으로 직접 전환하지 못하도록 제한하지 않는다는 가정을 완화합니다.
And finally, I’m amazed by what can be achieved in less than 80 lines of code with R…
As usual any comments welcome.
Risk as a “Survival Variable”
I come across a lot of strategies on the blogosphere some are interesting some are a complete waste of time but most share a common feature: people developing those strategies do their homework in term of analyzing the return but much less attention is paid to the risk side its random nature. I’ve seen comment like “a 25% drawdown in 2011 but excellent return overall”. Well my bet is that no one on earth will let you experience a 25% loss with their money (unless special agreements are in place). In the hedge fund world people have very low tolerance for drawdown. Generally, as a new trader in a hedge fund, assuming that you come with no reputation, you have very little time to prove yourself. You should make money from day 1 and keep on doing so for a few months before you gain a bit of credibility.
First let’s say you have a bad start and you lose money at the beginning. With a 10% drawdown you’re most certainly out but even with a 5% drawdown the chances of seeing your allocation reduced are very high. This has significant implications on your strategies. Let’s assume that if you lose 5% your allocation is divided by 2 and you come back to your initial allocation only when you passed the high water mark again (e. g. the drawdown comes back to 0). In the chart below I simulated the experiment with one of my strategies.
You start trading in 1st June 2003 and all goes well until 23rd Jul. 2003 where your drawdown curve hits the -5% threshold (**1**). Your allocation is cut by 50% and you don’t cross back the high water mark level until 05th Dec. 2003 (**3**). If you have kept the allocation unchanged, the high water mark level would have been crossed on 28th Oct. 2003 (**2**) and by the end of the year you would have made more money.
But let’s push the reasoning a bit further. Still on the chart above, assume you get really unlucky and you start trading toward mid-June 2003. You hit the 10% drawdown limit by the beginning of August and you’re most likely out of the game. You would have started in early August your allocation would not have been cut at all and you end up doing a good year in only 4 full months of trading. In those two examples nothing has changed but your starting date….
The trading success of any individual has some form of path dependency and there is not much you can do about it. However you can control the size of a strategy’s drawdown and this should be addressed with great care. A portfolio should be diversified in every possible dimension: asset classes, investment strategies, trading frequencies etc…. From that perspective risk is your “survival variable”. If managed properly you have a chance to stay in the game long enough to realise the potential of your strategy. Otherwise you won’t be there next month to see what happens.
The R Trader.
Using R and related tools in Quantitative Finance.
Archive for the ‘Trading Strategies’ 범주.
Linking R to IQFeed with the QuantTools package.
IQFeed provides streaming data services and trading solutions that cover the Agricultural, Energy and Financial marketplace. It is a well known and recognized data feed provider geared toward retail users and small institutions. The subscription price starts at around $80/month.
Stanislav Kovalevsky has developed a package called QuantTools. It is an all in one package designed to enhance quantitative trading modelling. It allows to download and organize historical market data from multiple sources like Yahoo, Google, Finam, MOEX and IQFeed. The feature that interests me the most is the ability to link IQFeed to R. I’ve been using IQFeed for a few years and I’m happy with it (I’m not affiliated to the company in any way). More information can be found here. I’ve been looking for an integration within R for a while and here it is. As a result, after I ran a few tests, I moved my code that was still in Python into R. Just for completeness, here’s a link that explains how to download historical data from IQFeed using Python.
QuantTools offers four main functionalities: Get market data, Store/Retrieve market data, Plot time series data and Back testing.
First make sure that IQfeed is open. You can either download daily or intraday data. The below code downloads daily prices (Open, High, Low, Close) for SPY from 1st Jan 2017 to 1st June 2017.
The below code downloads intraday data from 1st May 2017 to 3rd May 2017.
Note the period parameter. It can take any of the following values: tick, 1min, 5min, 10min, 15min, 30min, hour, day, week, month, depending on the frequency you need.
QuantTools makes the process of managing and storing tick market data easy. You just setup storage parameters and you are ready to go. The parameters are where, since what date and which symbols you would like to be stored. Any time you can add more symbols and if they are not present in a storage, QuantTools tries to get the data from specified start date. The code below will save the data in the following directory: “C:/Users/Arnaud/Documents/Market Data/iqfeed”. There is one sub folder by instrument and the data is aved in. rds files.
You can also store data between specific dates. Replace the last line of code above with one of the below.
Now should you want to get back some of the data you stored, just run something like:
Note that only ticks are supported in local storage so period must be ‘tick’
QuantTools provides plot_ts function to plot time series data without weekend, holidays and overnight gaps. In the example below, I first retrieve the data stored above, then select the first 100 price observations and finally draw the chart.
Two things to notice: First spy is a data. table object hence the syntax above. To get a quick overview of data. table capabilities have a look at this excellent cheat sheet from DataCamp. Second the local parameter is TRUE as the data is retrieved from internal storage.
QuantTools allows to write your own trading strategy using its C++ API. I’m not going to elaborate on this as this is basically C++ code. You can refer to the Examples section on QuantTools website.
Overall I find the package extremely useful and well documented. The only missing bit is the live feed between R and IQFeed which will make the package a real end to end solution.
As usual any comments welcome.
BERT: a newcomer in the R Excel connection.
A few months ago a reader point me out this new way of connecting R and Excel. I don’t know for how long this has been around, but I never came across it and I’ve never seen any blog post or article about it. So I decided to write a post as the tool is really worth it and before anyone asks, I’m not related to the company in any way.
BERT stands for Basic Excel R Toolkit. It’s free (licensed under the GPL v2) and it has been developed by Structured Data LLC. At the time of writing the current version of BERT is 1.07. More information can be found here. From a more technical perspective, BERT is designed to support running R functions from Excel spreadsheet cells. In Excel terms, it’s for writing User-Defined Functions (UDFs) in R.
In this post I’m not going to show you how R and Excel interact via BERT. There are very good tutorials here, here and here. Instead I want to show you how I used BERT to build a “control tower” for my trading.
My trading signals are generated using a long list of R files but I need the flexibility of Excel to display results quickly and efficiently. As shown above BERT can do this for me but I also want to tailor the application to my needs. By combining the power of XML, VBA, R and BERT I can create a good looking yet powerful application in the form of an Excel file with minimum VBA code. Ultimately I have a single Excel file gathering all the necessary tasks to manage my portfolio: database update, signal generation, orders submission etc… My approach could be broken down in the 3 steps below:
Use XML to build user defined menus and buttons in an Excel file. The above menus and buttons are essentially calls to VBA functions. Those VBA functions are wrapup around R functions defined using BERT.
With this approach I can keep a clear distinction between the core of my code kept in R, SQL and Python and everything used to display and format results kept in Excel, VBA & XML. In the next sections I present the prerequisite to developed such an approach and a step by step guide that explains how BERT could be used for simply passing data from R to Excel with minimal VBA code.
1 & # 8211; Download and install BERT from this link . Once the installation has completed you should have a new Add-Ins menu in Excel with the buttons as shown below. This is how BERT materialized in Excel.
2 & # 8211; Download and install Custom UI editor : The Custom UI Editor allows to create user defined menus and buttons in Excel ribbon. A step by step procedure is available here.
1 & # 8211; R Code: The below R function is a very simple piece of code for illustration purposes only. It calculates and return the residuals from a linear regression. This is what we want to retrieve in Excel. Save this in a file called myRCode. R (any other name is fine) in a directory of your choice.
2 & # 8211; functions. R in BERT : From Excel select Add-Ins -> Home Directory and open the file called functions. R . In this file paste the following code. Make sure you insert the correct path.
This is just sourcing into BERT the R file you created above. Then save and close the file functions. R. Should you want to make any change to the R file created in step 1 you will have to reload it using the BERT button “Reload Startup File” from the Add-Ins menu in Excel.
3 & # 8211; In Excel: Create and save a file called myFile. xslm (any other name is fine). This is a macro-enabled file that you save in the directory of your choice. Once the file is saved close it.
4 & # 8211; Open the file created above in Custom UI editor : Once the file is open, paste the below code.
You should have something like this in the XML editor:
Essentially this piece of XML code creates an additional menu (RTrader), a new group (My Group) and a user defined button (New Button) in the Excel ribbon. Once you’re done, open myFile. xslm in Excel and close the Custom UI Editor. You should see something like this.
5 & # 8211; Open VBA editor : In myFile. xlsm insert a new module. Paste the code below in the newly created module.
This erases previous results in the worksheet prior to coping new ones.
6 & # 8211; Click New Button : Now go back to the spreadsheet and in the RTrader menu click the “New Button” 단추. You should see something like the below appearing.
The guide above is a very basic version of what can be achieved using BERT but it shows you how to combine the power of several specific tools to build your own custom application. From my perspective the interest of such an approach is the ability to glue together R and Excel obviously but also to include via XML (and batch) pieces of code from Python, SQL and more. This is exactly what I needed. Finally I would be curious to know if anyone has any experience with BERT?
Trading strategy: Making the most of the out of sample data.
When testing trading strategies a common approach is to divide the initial data set into in sample data: the part of the data designed to calibrate the model and out of sample data: the part of the data used to validate the calibration and ensure that the performance created in sample will be reflected in the real world. As a rule of thumb around 70% of the initial data can be used for calibration (i. e. in sample) and 30% for validation (i. e. out of sample). Then a comparison of the in and out of sample data help to decide whether the model is robust enough. This post aims at going a step further and provides a statistical method to decide whether the out of sample data is in line with what was created in sample.
In the chart below the blue area represents the out of sample performance for one of my strategies.
A simple visual inspection reveals a good fit between the in and out of sample performance but what degree of confidence do I have in this? At this stage not much and this is the issue. What is truly needed is a measure of similarity between the in and out of sample data sets. In statistical terms this could be translated as the likelihood that the in and out of sample performance figures coming from the same distribution. There is a non-parametric statistical test that does exactly this: the Kruskall-Wallis Test . A good definition of this test could be found on R-Tutor “A collection of data samples are independent if they come from unrelated populations and the samples do not affect each other. Using the Kruskal-Wallis Test , we can decide whether the population distributions are identical without assuming them to follow the normal distribution.” The added benefit of this test is not assuming a normal distribution.
It exists other tests of the same nature that could fit into that framework. The Mann-Whitney-Wilcoxon test or the Kolmogorov-Smirnov tests would perfectly suits the framework describes here however this is beyond the scope of this article to discuss the pros and cons of each of these tests. A good description along with R examples can be found here.
Here’s the code used to generate the chart above and the analysis:
In the example above the in sample period is longer than the out of sample period therefore I randomly created 1000 subsets of the in sample data each of them having the same length as the out of sample data. Then I tested each in sample subset against the out of sample data and I recorded the p-values. This process creates not a single p-value for the Kruskall-Wallis test but a distribution making the analysis more robust. In this example the mean of the p-values is well above zero (0.478) indicating that the null hypothesis should be accepted: there are strong evidences that the in and out of sample data is coming from the same distribution.
As usual what is presented in this post is a toy example that only scratches the surface of the problem and should be tailored to individual needs. However I think it proposes an interesting and rational statistical framework to evaluate out of sample results.
This post is inspired by the following two papers:
Vigier Alexandre, Chmil Swann (2007), “Effects of Various Optimization Functions on the Out of Sample Performance of Genetically Evolved Trading Strategies”, Forecasting Financial Markets Conference.
Vigier Alexandre, Chmil Swann (2010), « An optimization process to improve in/out of sample consistency, a Stock Market case», JP Morgan Cazenove Equity Quantitative Conference, London October 2010.
Introducing fidlr: FInancial Data LoadeR.
fidlr is an RStudio addin designed to simplify the financial data downloading process from various providers. This initial version is a wrapper around the getSymbols function in the quantmod package and only Yahoo, Google, FRED and Oanda are supported. I will probably add functionalities over time. As usual with those things just a kind reminder: “THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND…”
How to install and use fidlr?
You can get the addin/package from its Github repository here (I will register it on CRAN later on) Install the addin. There is an excellent tutorial to install RStudio Addins here. Once the addin is installed it should appear in the Addin menu. Just chose fidlr in the menu and a window as pictured below should appear. Choose a data provider from the the Source dropdown menu. Select a date range from the Date menu Enter the symbol you wish to download in the instrument text box. To download several symbols just enter the symbols separated by commas. Use the Radio buttons to choose whether you want to download the instrument in a csv file or in the global environment. The csv file will be saved in the working directory and there will be one csv file per instrument. Press Run to get the data or Close to close down the addin.
Error messages and warnings are handled by the underlying packages (quantmod and Shiny) and can be read from the console.
This is a very first version of the project so do not expect perfection but hopefully it will get better over time. Please report any comment, suggestion, bug etc… to: thertradergmail.
Maintaining a database of price files in R.
Doing quantitative research implies a lot of data crunching and one needs clean and reliable data to achieve this. What is really needed is clean data that is easily accessible (even without an internet connection). The most efficient way to do this for me has been to maintain a set of csv files. Obviously this process can be handled in many ways but I found very efficient and simple overtime to maintain a directory where I store and update csv files. I have one csv file per instrument and each file is named after the instrument it contains. The reason I do so is twofold: First, I don’t want to download (price) data from Yahoo, Google etc… every time I want to test a new idea but more importantly once I identified and fixed a problem, I don’t want to have to do it again the next time I need the same instrument. Simple yet very efficient so far. The process is summarized in the chart below.
In everything that follows, I assume that data is coming from Yahoo. The code will have to be amended for data from Google, Quandl etc… In addition I present the process of updating daily price data. The setup will be different for higher frequency data and other type of dataset (i. e. different from prices).
1 & # 8211; Initial data downloading (listOfInstruments. R & historicalData. R)
The file listOfInstruments. R is a file containing only the list of all instruments.
If an instrument isn’t part of my list (i. e. no csv file in my data folder) or if you do it for the very first time you have to download the initial historical data set. The example below downloads a set of ETFs daily prices from Yahoo Finance back to January 2000 and store the data in a csv file.
2 & # 8211; Update existing data (updateData. R)
The below code starts from existing files in the dedicated folder and updates all of them one after the other. I usually run this process everyday except when I’m on holiday. To add a new instrument, simply run step 1 above for this instrument alone.
3 & # 8211; Create a batch file (updateDailyPrices. bat)
Another important part of the job is creating a batch file that automates the updating process above (I’m a Windows user). This avoids opening R/RStudio and run the code from there. The code below is placed on a. bat file (the path has to be amended with the reader’s setup). Note that I added an output file (updateLog. txt) to track the execution.
The process above is extremely simple because it only describes how to update daily price data. I’ve been using this for a while and it has been working very smoothly for me so far. For more advanced data and/or higher frequencies, things can get much trickier.
As usual any comments welcome.
Factor Evaluation in Quantitative Portfolio Management.
When it comes to managing a portfolio of stocks versus a benchmark the problem is very different from defining an absolute return strategy. In the former one has to hold more stocks than in the later where no stocks at all can be held if there is not good enough opportunity. The reason for that is the tracking error . This is defined as the standard deviation of the portfolio return minus the benchmark return. The less stocks is held vs. a benchmark the higher the tracking error (e. g higher risk).
The analysis that follows is largely inspired by the book “Active Portfolio Management” by Grinold & Kahn. This is the bible for anyone interested in running a portfolio against a benchmark. I strongly encourage anyone with an interest in the topic to read the book from the beginning to the end. It’s very well written and lays the foundations of systematic active portfolio management (I have no affiliation to the editor or the authors).
Here we’re trying to rank as accurately as possible the stocks in the investment universe on a forward return basis. Many people came up with many tools and countless variant of those tools have been developed to achieve this. In this post I focus on two simple and widely used metrics: Information Coefficient (IC) and Quantiles Return (QR).
The IC gives an overview of the factor forecasting ability. More precisely, this is a measure of how well the factor ranks the stocks on a forward return basis. The IC is defined as the rank correlation ( ρ ) between the metric (e. g. factor) and the forward return. In statistical terms the rank correlation is a nonparametric measure of dependance between two variables. For a sample of size n , the n raw scores are converted to ranks , and ρ is computed from:
The horizon for the forward return has to be defined by the analyst and it’s a function of the strategy’s turnover and the alpha decay (this has been the subject of extensive research). Obviously ICs must be as high as possible in absolute terms.
For the keen reader, in the book by Grinold & Kahn a formula linking Information Ratio (IR) and IC is given: with breadth being the number of independent bets (trades). This formula is known as the fundamental law of active management . The problem is that often, defining breadth accurately is not as easy as it sounds.
In order to have a more accurate estimate of the factor predictive power it’s necessary to go a step further and group stocks by quantile of factor values then analyse the average forward return (or any other central tendency metric) of each of those quantiles. The usefulness of this tool is straightforward. A factor can have a good IC but its predictive power might be limited to a small number of stocks. This is not good as a portfolio manager will have to pick stocks within the entire universe in order to meet its tracking error constraint. Good quantiles return are characterised by a monotonous relationship between the individual quantiles and forward returns.
All the stocks in the S&P500 index (at the time of writing). Obviously there is a survival ship bias: the list of stocks in the index has changed significantly between the start and the end of the sample period, however it’s good enough for illustration purposes only.
The code below downloads individual stock prices in the S&P500 between Jan 2005 and today (it takes a while) and turns the raw prices into return over the last 12 months and the last month. The former is our factor, the latter will be used as the forward return measure.
Below is the code to compute Information Coefficient and Quantiles Return. Note that I used quintiles in this example but any other grouping method (terciles, deciles etc…) can be used. it really depends on the sample size, what you want to capture and wether you want to have a broad overview or focus on distribution tails. For estimating returns within each quintile, median has been used as the central tendency estimator. This measure is much less sensitive to outliers than arithmetic mean.
And finally the code to produce the Quantiles Return chart.
3 & # 8211; How to exploit the information above?
In the chart above Q1 is lowest past 12 months return and Q5 highest. There is an almost monotonic increase in the quantiles return between Q1 and Q5 which clearly indicates that stocks falling into Q5 outperform those falling into Q1 by about 1% per month. This is very significant and powerful for such a simple factor (not really a surprise though…). Therefore there are greater chances to beat the index by overweighting the stocks falling into Q5 and underweighting those falling into Q1 relative to the benchmark.
An IC of 0.0206 might not mean a great deal in itself but it’s significantly different from 0 and indicates a good predictive power of the past 12 months return overall. Formal significance tests can be evaluated but this is beyond the scope of this article.
The above framework is excellent for evaluating investments factor’s quality however there are a number of practical limitations that have to be addressed for real life implementation:
Rebalancing : In the description above, it’s assumed that at the end of each month the portfolio is fully rebalanced. This means all stocks falling in Q1 are underweight and all stocks falling in Q5 are overweight relative to the benchmark. This is not always possible for practical reasons: some stocks might be excluded from the investment universe, there are constraints on industry or sector weight, there are constraints on turnover etc… Transaction Costs : This has not be taken into account in the analysis above and this is a serious brake to real life implementation. Turnover considerations are usually implemented in real life in a form of penalty on factor quality. Transfer coefficient : This is an extension of the fundamental law of active management and it relaxes the assumption of Grinold’s model that managers face no constraints which preclude them from translating their investments insights directly into portfolio bets.
And finally, I’m amazed by what can be achieved in less than 80 lines of code with R…
As usual any comments welcome.
Risk as a “Survival Variable”
I come across a lot of strategies on the blogosphere some are interesting some are a complete waste of time but most share a common feature: people developing those strategies do their homework in term of analyzing the return but much less attention is paid to the risk side its random nature. I’ve seen comment like “a 25% drawdown in 2011 but excellent return overall”. Well my bet is that no one on earth will let you experience a 25% loss with their money (unless special agreements are in place). In the hedge fund world people have very low tolerance for drawdown. Generally, as a new trader in a hedge fund, assuming that you come with no reputation, you have very little time to prove yourself. You should make money from day 1 and keep on doing so for a few months before you gain a bit of credibility.
First let’s say you have a bad start and you lose money at the beginning. With a 10% drawdown you’re most certainly out but even with a 5% drawdown the chances of seeing your allocation reduced are very high. This has significant implications on your strategies. Let’s assume that if you lose 5% your allocation is divided by 2 and you come back to your initial allocation only when you passed the high water mark again (e. g. the drawdown comes back to 0). In the chart below I simulated the experiment with one of my strategies.
You start trading in 1st June 2003 and all goes well until 23rd Jul. 2003 where your drawdown curve hits the -5% threshold (**1**). Your allocation is cut by 50% and you don’t cross back the high water mark level until 05th Dec. 2003 (**3**). If you have kept the allocation unchanged, the high water mark level would have been crossed on 28th Oct. 2003 (**2**) and by the end of the year you would have made more money.
But let’s push the reasoning a bit further. Still on the chart above, assume you get really unlucky and you start trading toward mid-June 2003. You hit the 10% drawdown limit by the beginning of August and you’re most likely out of the game. You would have started in early August your allocation would not have been cut at all and you end up doing a good year in only 4 full months of trading. In those two examples nothing has changed but your starting date….
The trading success of any individual has some form of path dependency and there is not much you can do about it. However you can control the size of a strategy’s drawdown and this should be addressed with great care. A portfolio should be diversified in every possible dimension: asset classes, investment strategies, trading frequencies etc…. From that perspective risk is your “survival variable”. If managed properly you have a chance to stay in the game long enough to realise the potential of your strategy. Otherwise you won’t be there next month to see what happens.
As usual any comments welcome.
A Simple Shiny App for Monitoring Trading Strategies – 파트 II.
This is a follow up on my previous post “A Simple Shiny App for Monitoring Trading Strategies“. I added a few improvements that make the app a bit better (at least for me!). Below is the list of new features :
A sample. csv file (the one that contains the raw data) A “EndDate” drop down box allowing to specify the end of the period. A “Risk” page containing a VaR analysis and a chart of worst performance over various horizons A “How To” page explaining how to use and tailor the app to individual needs.
I also made the app totally self contained. It is now available as a stand alone product and there is no need to have R/RStudio installed on your computer to run it. It can be downloaded from the R Trader Google drive account. This version of the app runs using portable R and portable Chrome. For the keen reader, this link explains in full details how to package a Shiny app into a desktop app (Windows only for now).
1 & # 8211; How to install & run the app on your computer.
Create a specific folder Unzip the contain of the. zip file onto that new folder. Change the paths in the runShinyApp file to match your setings To run the app, you just have launch the run. vbs file. I also included an icon (RTraderTradingApp. ico) should you want to create a shortcut on your desktop.
ui. R: controls the layout and appearance of the app server. R: contains the instructions needed to build the app. You can load as much strategies as you want as long as the corresponding csv file has the right format (see below). shinyStrategyGeneral. R: loads the required packages and launches the app.
3 & # 8211; How to add a trading strategy?
Create the corresponding. csv file in the right directory Create a new input in the data reactive function (within the server. R file) Add an extra element to the choice parameter in the first selectInput in the sidebarPanel (within the ui. R file). The element’s name should match the name of the new input above.
Remove the input in the data reactive function corresponding to the strategy you want to remove (within the server. R file) Remove the element in the choice parameter in the first selectInput in the sidebarPanel corresponding to the strategy you want to remove (within the ui. R file).
Please feel free to get in touch should you have any suggestion.
A Simple Shiny App for Monitoring Trading Strategies.
In a previous post I showed how to use R, Knitr and LaTeX to build a template strategy report. This post goes a step further by making the analysis interactive. Besides the interactivity, the Shiny App also solves two problems :
I can now access all my trading strategies from a single point regardless of the instrument traded. Coupled with the Shiny interactivity, it allows easier comparison. I can focus on a specific time period.
The code used in this post is available on a Gist/Github repository. There are essentially 3 files.
ui. R : controls the layout and appearance of the app. server. R : contains the instructions needed to build the app. It loads the data and format it. There is one csv file per strategy each containing at least two columns: date and return with the following format: (“2010-12-22″,”0.04%” ). You can load as much strategies as you want as long as they have the right format. shinyStrategyG eneral. R : loads the required packages and launches the app.
This app is probably far from perfect and I will certainly improve it in the future. Feel free to get in touch should you have any suggestion.
A big thank you to the RStudio/Shiny team for such a great tool.
Using Genetic Algorithms in Quantitative Trading.
The question one should always asked him/herself when using technical indicators is what would be an objective criteria to select indicators parameters (e. g., why using a 14 days RSI rather than 15 or 20 days?). Genetic algorithms (GA) are well suited tools to answer that question. In this post I’ll show you how to set up the problem in R. Before I proceed the usual reminder: What I present in this post is just a toy example and not an invitation to invest. It’s not a finished strategy either but a research idea that needs to be further researched, developed and tailored to individual needs.
What are genetic algorithms?
The best description of GA I came across comes from Cybernatic Trading a book by Murray A. Ruggiero. “Genetic Algorithms were invented by John Holland in the mid-1970 to solve hard optimisation problems. This method uses natural selection, survival of the fittest”. The general process follows the steps below:
Encode the problem into chromosomes Using the encoding, develop a fitness function for use in evaluating each chromosome’s value in solving a given problem Initialize a population of chromosomes Evaluate each chromosome in the population Create new chromosomes by mating two chromosomes. This is done by muting and recombining two parents to form two children (parents are selected randomly but biased by their fitness) Evaluate the new chromosome Delete a member of the population that is less fit than the new chromosome and insert the new chromosome in the population. If the stop criteria is reached (maximum number of generations, fitness criteria is good enough…) then return the best chromosome alternatively go to step 4.
From a trading perspective GA are very useful because they are good at dealing with highly nonlinear problems. However they exhibit some nasty features that are worth mentioning:
Over fitting: This is the main problem and it’s down to the analyst to set up the problem in a way that minimises this risk. Computing time : If the problem isn’t properly defined, it can be extremely long to reach a decent solution and the complexity increases exponentially with the number of variables. Hence the necessity to carefully select the parameters.
There are several R packages dealing with GA, I chose to use the most common one: rgenoud.
Daily closing prices for most liquid ETFs from Yahoo finance going back to January 2000. The in sample period goes from January 2000 to December 2010. The Out of sample period starts on January 2011.
The logic is as following: the fitness function is optimised over the in sample period to obtain a set of optimal parameters for the selected technical indicators. The performance of those indicators is then evaluated in the out of sample period. But before doing so the technical indicators have to be selected.
The equity market exhibits two main characteristics that are familiar to anyone with some trading experience. Long term momentum and short term reversal. Those features can be translated in term of technical indicators by: moving averages cross over and RSI. This represents a set of 4 parameters: Look-back periods for long and short term moving averages, look-back period for RSI and RSI threshold. The sets of parameters are the chromosomes . The other key element is the fitness function . We might want to use something like: maximum return or Sharpe ratio or minimum average Drawdown. In what follows, I chose to maximise the Sharpe ratio.
The R implementation is a set of 3 functions:
fitnessFunction : defines the fitness function (e. g., maximum Sharpe ratio) to be used within the GA engine tradingStatistics : summary of trading statistics for the in and out of sample periods for comparison purposes genoud : the GA engine from the rgenoud package.
The genoud function is rather complex but I’m not going to explain what each parameter means as I want to keep this post short (and the documentation is really good).
In the table below I present for each instrument the optimal parameters (RSI look-back period, RSI threshold, Short Term Moving Average, and Long Term Moving Average) along with the in and out of sample trading statistics.
Before commenting the above results, I want to explain a few important points. To match the logic defined above, I bounded the parameters to make sure the look-back period for the long term moving average is always longer that the shorter moving average. I also constrained the optimiser to choose only the solutions with more than 50 trades in the in sample period (e. g;, statistical significance).
Overall the out of sample results are far from impressive. The returns are low even if the number of trades is small to make the outcome really significant. However there’s a significant loss of efficiency between in and out of sample period for Japan (EWJ) which very likely means over fitting.
This post is intended to give the reader the tools to properly use GA in a quantitative trading framework. Once again, It’s just an example that needs to be further refined. A few potential improvement to explore would be:
fitness function : maximising the Sharpe ratio is very simplistic. A “smarter” function would certainly improve the out of sample trading statistics pattern : we try to capture a very straightforward pattern. A more in depth pattern research is definitely needed. optimisation : there are many ways to improve the way the optimisation is conducted. This would improve both the computation speed and the rationality of the results.
The code used in this post is available on a Gist repository.
Comments
Post a Comment