Tuesday 6 March 2018

Sql 거래 전략


SQL 거래 전략
App Store를 통해 가져 오기 우리의 응용 프로그램 에서이 게시물을 읽으십시오!
quantmod를 사용하여 R에서 새로운 거래 전략을 커스터마이징하기.
R의 주식 기호에 새로운 TA 표식을 만들고 싶습니다. 그러나 SQL 조건부 전략을 R 자체 정의 함수로 변환하고 R의 ChartSeries에 추가하는 방법에 대해서는 잘 모릅니다.
질문은 다음 코드에 설명으로 나열되어 있습니다.
질문 : 아래 코드를 R의 함수로 사용하려면 어떻게 다시 작성해야합니까?
나는이 경우 SQL을 필요로하지 않는다고 생각한다.
나는 REF가 무엇을 의미하는지 모르겠다. 그러나 나는 너 자신에 의해 그렇게 할 수있을 것이라고 확신한다.
이것은 출력 (나는 사진을 업로드하는 것처럼 보이지 않지만 신호 eq 1이있는 수평선이있는 차트를 보게됩니다)
이 함수를 sqldf 패키지의 sqldf ()에 대한 래퍼로 사용하십시오. sqldf ()에 대한 인수는 데이터가있는 데이터 프레임의 select 문입니다.
이에 대한 좋은 설명서는 Burns Statistics에서 찾을 수 있습니다.

SQL 거래 전략
App Store를 통해 가져 오기 우리의 응용 프로그램 에서이 게시물을 읽으십시오!
SQL Server의 이상적인 인덱싱 전략은 무엇입니까?
친구이자 SQL Server를 사용하는 새 프로젝트를 만들고 있습니다. 과거 프로젝트에서 수행 한 SQL에서 JOIN 또는 WHERE에서 사용되는 모든 필드에 항상 인덱스를 넣었습니다.
내 친구가 그들을 위해 성능 요구가있을 때만 그들을 추가했습니다. 인덱스를 유지 관리하는 데 비용이 소요된다는 생각이 들며 비용을 지불 할 가치가 있는지 확인하고자합니다. 일부 쿼리는 자주 사용되지 않을 것이고 일부 테이블은 다른 테이블보다 더 적극적으로 추가 될 것이라고 말하는 것은 공평합니다.
따라서 나는 데이터베이스 인덱스에 대한 "베스트 프랙티스"가 무엇인지에 대한 조언을 구하고 있습니다. 너에게 잘 맞는 것은 무엇인가?
내 개인적인 취향은 적극적 접근 방식입니다. 쿼리를 기반으로 필요한 경우 인덱스를 추가하십시오. 당신이 말하는 것처럼, JOINs 또는 WHEREs에 관련된 분야에. 모든 색인은 읽기 조회 속도를 높여 주지만 쓰기 작업은 느려집니다 (모든 쓰기가 색인을 업데이트해야하므로). 따라서 쓰기 집약적 인 테이블의 경우 다른 솔루션 (데이터웨어 하우징, 복제)이 필요할 수 있습니다.
성능에 필요한 인덱스 만 추가하는 다른 방법은 활성 모니터링을 수행하는 경우에만 유효하지만 몇 가지 단점이 있습니다.
성능 문제가있는 테이블에 인덱스를 추가해야합니다. 색인이 추가되는 동안 테이블은 잠겨 있습니다. 이 테이블은 많이 사용되는 테이블입니다! 종종 테스트 할 때 테스트 데이터는 응용 프로그램의 실제 데이터보다 몇 배 더 작습니다. 병목 현상이 간과 될 위험이 있습니다.
나는 다음 지침을 따르려고 노력할 것이다.
항상 좋은 기본 / 클러스터링 키 - 일반적으로 INT IDENTITY - GUID 또는 대형 화합물 PK / CK를 피하십시오. 훌륭하고 신중하게 선택한 PK / CK는 전반적인 성능 향상에 도움이 될 것입니다. 그 이유를 철저히 이해하려면 핵심 옵션 클러스터링에 대한 Kimberly Tripp의 블로그 게시물을 모두 읽으십시오.
항상 모든 외래 키 열을 색인화합니다. 이것은 JOIN 성능에 도움이됩니다.
그것보다 다른 : less는 더 많습니다! 절대적으로 필요한 경우에만 색인을 추가하십시오. 시스템을 관찰하고, 데이터로드를 프로파일하고, 성능을 확인하고, 미세 조정하고, 다시 측정하십시오. 색인 도움 - 그것을 지키십시오; 색인이 사용되지 않으면 던지십시오.
(DMV 누락 및 DMV 사용) DMV를 사용하여 색인이 도움이되는지, 어떤 색인이 사용되지 않는지에 대한 아이디어를 얻으십시오.
당신은 그것들에 대해 많은 질의를하는 컬럼이나 컬럼 그룹에만 그것들을 넣고 싶습니다. SQL Server에서 많은 쿼리를 실행하여 테이블에 대해 실행되는 쿼리를 확인할 수 있으며 SQL Server는 인덱스가없는 인덱스를 제안하기도합니다.
다음은 유용한 정보와 좋은 정보로 연결되는 링크입니다. SQL Server 인덱스 검사 목록 및 팁.
귀하의 질문에 대한 쉬운 대답은 없습니다. 그것은 모두 테이블 사용으로 이어집니다. 테이블 사용을 모니터링하면 수행 할 작업을 알려줍니다.
sys. dm_db_missing_index_details에서 *를 선택하십시오.
동적 관리 뷰를 파악하십시오.
또한 어떤 사람들이 '커버 된 인덱스'에 대해 말하고있는 것은 커버 된 인덱스 (SQL 2000)와 INCLUDE 절 (SQL 2005 이상)을 사용하는 인덱스의 차이를 이해하고 있는지 확인하는 것입니다.
색인은 가능한 한 고유 한 값에 가장 적합합니다. 예를 들어, 열의 50 %가 값 'A'이고 열의 50 %가 'B'값을 갖는 열에 색인을 배치하는 것은 쓸모가 없습니다.
이렇게하면 테이블에서 올바른 값을 선택하기 전에 레코드의 50 % 이상을 스캔합니다.
그러므로 가장 좋은 방법은 가장 고유 한 열과 쿼리를 선택하는 데 사용 된 열에 만 인덱스를 배치하는 것입니다.
예 : 일반적인 "로그인"에 대한 select를 만들려면 사용자 이름이 고유한지 확인하기 위해 "사용자 이름"열에 색인을 붙이십시오.
색인을 디자인 할 때 다음 지침을 따르십시오.
수많은 행이있는 테이블, 쿼리의 WHERE 절 또는 테이블 조인에서 사용되는 열과 ORDER BY 및 GROUP BY 쿼리에서 사용되는 열의 인덱스를 사용합니다. 자주 업데이트되는 열에서는 자주 사용되지 않는 색인을 피하십시오. 또한 자주 업데이트되는 테이블에 많은 인덱스가 생기지 않도록하십시오. 그렇지 않으면 불필요하게 쿼리의 삽입 및 업데이트 시간이 늘어납니다. 성능을 향상 시키려면 인덱싱 된 열의 전체 너비를 최소화하십시오. 클러스터형 및 비 클러스터형 인덱스를 적절히 사용하십시오. 각각의 목적을 이해하고 시나리오에 맞는 유형을 선택하십시오. 자주 사용되는 명령문의 쿼리 실행 시간을 줄이려면 커버 인덱스를 사용하십시오. 커버링 인덱스는 WHERE 절과 쿼리 열 선택에있는 모든 열을 포함하는 비 클러스터형 인덱스입니다.

QuantStart.
빠르게 성장하는 소매점 퀀텀 트레이더 커뮤니티를 지원하는 Quantcademy 개인 회원 포털에 가입하십시오. 당신은 당신의 가장 중요한 퀀트 트레이딩 질문에 대답 할 준비가되어있는 지식이 풍부하고 마음이 맞는 퀀트 트레이더 그룹을 찾을 수 있습니다.
퀀트 트레이딩에 관한 나의 eBook을 확인해보십시오. 여기서 저는 파이썬 툴로 수익성 높은 체계적인 트레이딩 전략을 만드는 법을 가르쳐드립니다.
Python 및 R을 사용하여 시계열 분석, 기계 학습 및 베이지안 통계를 사용하는 고급 거래 전략에 관한 새로운 전자 책을 살펴보십시오.
2013 년 4 월 19 일 Michael Halls-Moore 작성
이 기사에서는 수익성있는 알고리즘 거래 전략을 식별하는 방법을 소개하고자합니다. 오늘 우리의 목표는 그러한 시스템을 찾고 평가하고 선택하는 방법을 자세하게 이해하는 것입니다. 어떻게 전략을 식별하는 것이 개인의 선호에 관한 것인가, 전략 수행 성과, 테스트를위한 과거 데이터의 유형과 양을 결정하는 방법, 거래 전략을 냉정하게 평가하는 방법, 마지막으로 백 테스트 단계로 진행하는 방법에 대해 설명합니다. 전략 구현.
거래를위한 자신 만의 개인 선호도 확인.
성공적인 거래자가되기 위해서는 - 임의적으로 또는 알고리즘 적으로 - 정직한 질문을하는 것이 필요합니다. 트레이딩은 놀라운 속도로 돈을 잃을 수있는 능력을 제공하므로 선택한 전략을 이해하는 데 필요한만큼 "자신을 알아야합니다".
나는 거래에서 가장 중요한 고려 사항이 자신의 성격을 인식하고 있다고 말할 수 있습니다. 특히 거래 및 알고리즘 거래는 상당한 수준의 규율, 인내심 및 정서적 인 분리가 필요합니다. 알고리즘이 당신을 위해 당신의 거래를 수행하게하기 때문에, 그것이 실행될 때 전략에 간섭하지 않도록 해결할 필요가 있습니다. 이것은 특히 드로우 다운이 연장 된 기간에 매우 어려울 수 있습니다. 그러나 백 테스트에서 수익성이 높은 것으로 입증 된 많은 전략은 단순한 간섭으로 인해 망가질 수 있습니다. 당신이 알고리즘 트레이딩의 세계에 들어가기를 원한다면 감정적으로 테스트 될 것이며 성공하기 위해서는 이러한 어려움을 극복해야한다는 것을 이해하십시오!
다음 고려 사항은 시간 중 하나입니다. 풀 타임 직업이 있습니까? 파트 타임으로 일하십니까? 당신은 집에서 일하거나 매일 통근 통근을합니까? 이러한 질문은 귀하가 추구해야 할 전략의 빈도를 결정하는 데 도움이됩니다. 정규직 근무자의 경우, 일일 선물 전략이 적절하지 않을 수 있습니다 (적어도 완전히 자동화 될 때까지!). 시간 제약으로 인해 전략의 방법론이 결정됩니다. 당신의 전략이 빈번히 거래되고 값 비싼 뉴스 피드 (예 : 블룸버그 터미널)에 의존한다면 분명히 사무실에서이 전략을 성공적으로 실행할 수있는 능력에 대해 현실적이어야합니다! 많은 시간을 투자 한 사람들이나 전략을 자동화하는 기술을 배우려면보다 기술적 인 고 빈도 거래 (HFT) 전략을 고려할 수 있습니다.
일관되게 수익성있는 포트폴리오를 유지하려면 거래 전략에 대한 지속적인 연구가 필요하다는 것이 나의 믿음입니다. "전략의 밑에 레이다"영원히 체재하십시오. 따라서 거래에 할당되는 상당 부분은 지속적인 연구 수행에 있습니다. 강력한 수익성 또는 손실에 대한 완만 한 쇠퇴의 차이가 될 수 있기 때문에 이것을 할 준비가되어 있는지 여부를 자문 해보십시오.
또한 거래 자본을 고려해야합니다. 양적 전략에 대해 일반적으로 받아 들여지는 이상적인 최소 금액은 50,000 USD입니다 (영국에서는 약 £ 35,000). 제가 다시 시작한다면, 아마 더 많은 금액, 아마 100,000 USD (약 £ 70,000)로 시작합니다. 그 이유는 중개 및 고주파 전략에서 거래 비용이 극도로 비싸기 때문이며 인출시 자본을 충분히 흡수 할 필요가 있기 때문입니다. 10,000 달러 미만으로 시작하는 것을 고려하고 있다면 거래 비용이 급격하게 수익에 반영되므로 하나 또는 두 개의 자산으로 거래하는 저주파 전략으로 제한해야합니다. 인터랙티브 브로커는 프로그래밍 기술을 가진 사람들에게 가장 친숙한 중개업자 중 하나 인 API로 인해 소매 계좌 최소 10,000 USD를 보유하고 있습니다.
프로그래밍 기술은 자동화 된 알고리즘 거래 전략을 수립하는 데 중요한 요소입니다. C ++, Java, C #, Python 또는 R과 같은 프로그래밍 언어에 익숙하면 엔드 투 엔드 데이터 저장소, 백 테스트 엔진 및 실행 시스템을 직접 만들 수 있습니다. 여기에는 여러 가지 장점이 있는데, 그 중 하나는 거래 인프라의 모든 측면을 완전히 인식 할 수있는 능력입니다. 또한 "기술 스택"을 완벽하게 제어 할 수 있도록 고주파수 전략을 탐색 할 수 있습니다. 이는 자신의 소프트웨어를 테스트하고 버그를 제거 할 수 있음을 의미하지만, 적어도 알 고 트레이딩 경력의 초기 부분에서는 인프라를 코딩하는 데 더 많은 시간을 소비하고 전략을 구현하는 데 더 적은 시간을 소비합니다. Excel 또는 MATLAB 거래가 편리하고 다른 구성 요소의 개발을 아웃소싱 할 수 있습니다. 그러나 나는 특히 높은 빈도로 거래하는 사람들에게 이것을 권장하지 않습니다.
알고리즘 거래를 통해 무엇을 성취하고자하는지 스스로 자문 해봐야합니다. 정기 수입에 관심이 있습니까? 이를 통해 귀하의 트레이딩 계좌에서 수입을 얻을 수 있습니다. 또는 장기 자본 이득에 관심이 있습니까? 그리고 자금을 인출 할 필요없이 거래 할 수 있습니까? 소득 의존성은 전략의 빈도를 결정합니다. 보다 정기적으로 수입을 인출하려면 변동성이 적은 (즉, 높은 Sharpe 비율) 고주파 거래 전략이 필요합니다. 장기 트레이더는보다 조용한 거래 빈도를 제공 할 수 있습니다.
마지막으로, 짧은 시간 안에 극도로 부유하게되는 개념에 속지 마십시오! Algo 거래는 부유 한 빠른 계획이 아닙니다. 무엇이든지 가난한 빠른 계획이 될 수있는 경우. 알고리즘 거래에 성공하려면 상당한 훈련, 연구, 부지런함 및 인내가 필요합니다. 일관성있는 수익성을 창출하는 데 몇 년이 걸릴 수도 있습니다.
소싱 알고리즘 거래 아이디어.
반대로 일반적인 인식에도 불구하고, 실제로 공개 도메인에서 수익성있는 거래 전략을 찾는 것은 매우 직접적입니다. 결코 오늘보다 더 쉽게 거래 아이디어를 구할 수 없었습니다. 학술 재무 저널, 인쇄 전 서버, 거래 블로그, 거래 포럼, 주간 거래 잡지 및 전문 텍스트는 아이디어를 바탕으로 수천 가지의 거래 전략을 제공합니다.
양적 거래 연구자로서의 우리의 목표는 지속적인 거래 아이디어를 제공 할 수있는 전략 파이프 라인을 수립하는 것입니다. 이상적으로 우리는 우리가 만나는 전략을 소싱, 평가 및 구현하는 체계적인 접근 방식을 만들고 싶습니다. 파이프 라인의 목표는 일정한 양의 새로운 아이디어를 생성하고 최소한의 감정적 인 배려로 이러한 아이디어의 대부분을 거부 할 수있는 틀을 제공하는 것입니다.
우리는인지 적 편향이 의사 결정 방법에 영향을 미치지 않도록 극도로주의해야합니다. 이것은 하나의 자산 클래스를 다른 자산 클래스보다 선호하는 것처럼 간단 할 수 있습니다 (금 및 기타 귀금속이 마음에 들었습니다). 우리의 목표는 항상 긍정적 인 기대와 함께 지속적으로 수익성 높은 전략을 찾는 것입니다. 자산 클래스의 선택은 거래 자본 제약, 중개 수수료 및 레버리지 기능과 같은 다른 고려 사항을 기반으로해야합니다.
당신이 무역 전략의 개념에 완전히 익숙하지 않다면 처음 보는 것은 설립 된 교과서를 사용하는 것입니다. 클래식 텍스트는 양적 거래에 익숙해 지도록보다 간단하고 직관적 인 다양한 아이디어를 제공합니다. 다음은 목록을 통해 작업 할 때 점차 정교 해지는 양적 거래에 익숙하지 않은 사람들에게 내가 추천하는 선택입니다.
양적 거래 도서 목록을 더 보려면 QuantStart 독서 목록을 방문하십시오.
다음으로는 거래 포럼 및 거래 블로그를 통해보다 정교한 전략을 찾을 수 있습니다. 그러나주의 사항 : 많은 거래 블로그는 기술 분석의 개념에 의존합니다. 기술적 분석에는 자산 가격의 추세 또는 반전 패턴을 결정하기 위해 기본 지표 및 행동 심리를 활용하는 것이 포함됩니다.
전체 거래 공간에서 매우 인기가 있음에도 불구하고 기술적 분석은 양적 금융 분야에서 다소 비효율적 인 것으로 간주됩니다. 일부 사람들은 별자리를 읽거나 예측력면에서 차잎을 연구하는 것보다 낫지 않다고 제안했습니다. 실제로 기술적 인 분석을 이용하는 성공적인 개인이 있습니다. 그러나보다 정교한 수학 및 통계 툴박스를 갖춘 콴트로서 우리는 그러한 "TA 기반"전략의 효과를 쉽게 평가하고 정서적 고려 또는 선입견에 기초하지 않고 데이터 기반 결정을 내릴 수 있습니다.
다음은 잘 알려진 알고리즘 거래 블로그 및 포럼의 목록입니다.
보다 간단한 전략을 평가 한 경험이 있으면보다 정교한 학업을 검토해야합니다. 구독료가 높거나 일회성 비용이 들지 않으면 일부 학술지에 액세스하기 어려울 수 있습니다. 대학의 회원 또는 동창 인 경우 이러한 재정적 저널 중 일부에 대한 액세스 권한을 얻을 수 있어야합니다. 그렇지 않으면 동료 검토가 진행되는 학술 논문 초안의 인터넷 저장소 인 인쇄 전 서버를 볼 수 있습니다. 우리가 성공적으로 복제하고 수익을 얻으려는 전략에만 관심이 있기 때문에 동료 평가는 우리에게별로 중요하지 않습니다.
학술 전략의 주된 단점은 종종 시대에 뒤떨어 지거나 모호하고 값 비싼 과거 데이터가 필요하거나 비유 동 자산 클래스에서 거래되거나 수수료, 미끄러짐 또는 확산을 고려하지 않을 수 있다는 것입니다. 또한 거래 전략이 시장 주문, 주문 제한 또는 중지 손실 등을 포함하는지 여부도 분명하지 않을 수 있습니다. 따라서 가능한 한 최선을 다해 전략을 반복적으로 재 테스트하고 현실적인 거래를 추가하는 것이 절대적으로 중요합니다 당신이 거래하고자하는 자산 클래스의 많은 양상을 포함하는 비용.
다음은 아이디어를 얻을 수있는 인기있는 사전 인쇄 서버 및 재무 저널 목록입니다.
자신의 양적 전략을 수립하는 것은 어떻습니까? 일반적으로 다음 범주 중 하나 이상의 전문 지식이 필요합니다.
시장 미세 구조 - 특히 고주파 전략의 경우 시장 미세 구조, 즉 수익성을 창출하기 위해 주문서 역학을 이해할 수 있습니다. 각기 다른 시장에는 다양한 기술 제한, 규제, 시장 참여자 및 특정 전략을 통한 착취에 대한 제약이 있습니다. 이것은 매우 정교한 분야이며, 소매업 종사자는이 분야에서 경쟁이 어렵다는 것을 알게 될 것입니다. 특히, 경쟁에는 강력한 기술적 능력을 갖춘 대규모의 잘 자본화 된 양적 헤지 펀드가 포함됩니다. 펀드 구조 - 연금 펀드, 민간 투자 파트너십 (헤지 펀드), 상품 거래 자문 및 뮤추얼 펀드와 같은 공동 투자 펀드는 대규모 규제와 대규모 자본 보유로 인해 제약을받습니다. 따라서 좀 더 민첩한 사람에게는 일정한 일관된 행동이 악용 될 수 있습니다. 예를 들어, 대규모 자금은 규모 때문에 용량 제약을받을 수 있습니다. 따라서 대량의 유가 증권을 신속하게 적재 (판매)해야하는 경우 "시장 이동"을 피하기 위해 비틀 거리게됩니다. 정교한 알고리즘은 자금 구조 차익 거래로 알려진 일반적인 프로세스에서이 특이성 및 다른 특질을 이용할 수 있습니다. 기계 학습 / 인공 지능 - 최근 몇 년 동안 금융 시장에서 기계 학습 알고리즘이 널리 보급되었습니다. Naive-Bayes 등의 분류 자 ​​(Classifier)와 비선형 함수 계산자 (신경망) 및 최적화 루틴 (유전 알고리즘)은 모두 자산 경로를 예측하거나 거래 전략을 최적화하는 데 사용되었습니다. 이 분야에 대한 배경 지식이 있다면 특정 알고리즘이 특정 시장에 어떻게 적용될 수 있는지에 대한 통찰력을 가질 수 있습니다.
물론 퀀트가 조사 할 수있는 많은 분야가있다. 이후 기사에서 맞춤 전략을 세우는 방법에 대해 자세히 설명합니다.
매주 또는 심지어 매일 이러한 소스를 지속적으로 모니터링함으로써 다양한 소스의 일관된 전략 목록을받을 수 있습니다. 다음 단계는 시간 낭비를 최소화하고 수익성이 없을 것으로 예상되는 전략에 대한 자원을 다시 테스트하는 방법으로 이러한 전략의 큰 부분 집합을 거부하는 방법을 결정하는 것입니다.
거래 전략 평가.
첫 번째, 그리고 틀림없이 가장 분명한 고려 사항은 실제로 전략을 이해하는지 여부입니다. 간결하게 전략을 설명 할 수 있습니까? 아니면 일련의 경고와 끝없는 매개 변수 목록이 필요합니까? 또한, 전략은 실제로 좋은, 견고한 기반을 가지고 있습니까? 예를 들어, 당신이 시도하고있는 패턴을 유발할 수있는 행동 적 근거 또는 자금 구조 제약을 지적 할 수 있습니까? 이 제약은 극적인 규제 환경의 혼란과 같은 정권 교체를 견디겠습니까? 전략은 복잡한 통계 또는 수학적 규칙에 의존합니까? 모든 금융 시계열에 적용됩니까 아니면 수익성이 있다고 주장되는 자산 클래스에만 해당합니까? 새로운 거래 방법을 평가할 때 이러한 요소에 대해 끊임없이 생각해야합니다. 그렇지 않으면 무익한 전략을 백 테스팅하고 최적화하는 데 많은 시간을 낭비 할 수 있습니다.
일단 전략의 기본 원칙을 이해했다면, 앞서 언급 한 성격 프로파일에 맞는지 여부를 결정해야합니다. 이것은 소리가 나지 않는 막연한 고려 사항은 아닙니다! 전략은 성능 특성이 크게 다를 것입니다. 더 중요한 기간의 인출을 처리하거나보다 큰 수익을 위해 더 큰 위험을 감수하고자하는 특정 성격 유형이 있습니다. 우리가 퀀트 (quants)로서 가능한 한 많은인지 적 편향을 시도하고 제거하고, 전략을 조심스럽게 평가할 수 있어야 함에도 불구하고, 편향은 항상 내재되어 있습니다. 따라서 우리는 전략의 성과를 평가할 수있는 일관성 있고 감정적 인 수단이 필요합니다 . 다음은 내가 잠재적 인 새로운 전략을 판단 할 수있는 기준 목록입니다.
방법론 - 전략 모멘텀은 시장 중심, 방향성, 방향성이 있습니까? 전략은 이해하기 어렵고 통계에서 박사 학위를 요구하는 정교한 (또는 복잡한!) 통계 또는 기계 학습 기술에 의존합니까? 이러한 기술로 인해 상당한 양의 매개 변수가 도입되어 최적화 편향으로 이어질 수 있습니까? 전략이 체제 변화 (즉, 금융 시장의 잠재적 새로운 규제)에 견딜 수있을 것인가? Sharpe Ratio - Sharpe 비율은 경험적으로 전략의 보상 / 위험 비율의 특성을 나타냅니다. 그것은 주식 곡선에 의해 견디는 변동성 수준에 대해 얼마나 많은 수익을 낼 수 있는지를 정량화합니다. 당연히, 우리는 이러한 수익률과 변동성 (즉, 표준 편차)이 측정되는 기간과 빈도를 결정해야합니다. 보다 높은 빈도 전략은 표준 편차의 샘플링 속도가 더 빨라지지만 예를 들어 전체 측정 시간이 더 짧아야합니다. 레버리지 - 수익성을 위해 전략에 상당한 영향력이 필요합니까? 전략은 수익을 내기 위해 레버리지 파생 상품 (선물, 옵션, 스왑)의 사용을 필요로합니까? 이러한 레버리지 계약은 큰 변동성을 특징으로 할 수 있으므로 마진 콜을 쉽게 이끌 수 있습니다. 그러한 변동성에 대한 거래 자본과 기질이 있습니까? 빈도 - 전략의 빈도는 기술 스택 (기술적 전문성), 샤프 비율 및 전반적인 거래 비용 수준과 밀접하게 관련되어 있습니다. 고려해야 할 다른 모든 문제, 높은 빈도 전략은 더 많은 자본을 필요로하며, 구현하기가 더 정교하고 어렵습니다. 그러나 백 테스팅 엔진이 정교하고 버그가없는 것으로 가정하면 훨씬 높은 Sharpe 비율을 갖게됩니다. 변동성 - 변동성은 전략의 "위험"과 강하게 관련됩니다. Sharpe 비율은 이것을 특징으로합니다. 기초 자산 군의 변동성이 크지 않다면 주식 곡선의 변동성이 커지며 샤프 비율도 작아진다. 나는 물론 긍정적 인 변동성이 거의 네거티브 변동성과 같다고 가정하고 있습니다. 일부 전략은 더 큰 불리한 변동성을 가질 수 있습니다. 이러한 속성을 알고 있어야합니다. 승패, 평균 손익 - 전략은 승패와 평균 손익 특성이 다릅니다. 잃어버린 거래의 수가 승리 한 거래의 수를 초과하더라도 매우 수익률 높은 전략을 가질 수 있습니다. 기세 전략은 수익성이 있기 위해 소수의 "대히트"에 의존하기 때문에이 패턴을 갖는 경향이 있습니다. 평균 회귀 전략은 거래가 "승리자"인 경우 반대되는 경향이 있지만 손실 거래는 매우 심할 수 있습니다. 최대 인출 - 최대 인출은 전략의 지분 곡선에서 가장 큰 전체적인 최저가 하락률입니다. 기세 전략은 장기간의 축소 (많은 증분 손실 거래로 인한 손실)로 고통받는 것으로 잘 알려져 있습니다. 역사적인 테스트에서 이것이 전략과 관련하여 "통상적 인 업무"라고 제안한 경우에도 많은 상인은 연장 된 인출 기간에 포기할 것입니다. 당신은 당신의 전략 거래를 중단하기 전에 어느 정도의 연체율 (그리고 어느 기간 동안)을 받을지 결정할 필요가 있습니다. 이는 매우 개인적인 결정이므로 신중하게 고려해야합니다. 용량 / 유동성 - 소매 수준에서, 당신이 (비상주 주식처럼) 고도로 유동성이없는 수단으로 거래하지 않는 한, 당신은 전략 능력에 크게 신경 쓰지 않아도됩니다. 용량은 전략의 추가 자본에 대한 확장 성을 결정합니다. 대형 헤지 펀드의 대부분은 자본 배분에서 전략이 증가함에 따라 상당한 용량 문제로 어려움을 겪습니다. 매개 변수 - 특정 전략 (특히 기계 학습 커뮤니티에있는 전략)에는 많은 양의 매개 변수가 필요합니다. 전략에 필요한 추가 매개 변수가 있으면 최적화 바이어스 ( "곡선 맞춤"이라고도 함)에 취약 해집니다. 가능한 한 적은 수의 매개 변수로 전략을 타겟팅하고 전략을 테스트 할 수있는 충분한 양의 데이터가 있는지 확인해야합니다. 벤치 마크 - 거의 모든 전략 ( "절대 수익"으로 특징 지우지 않는 한)은 일부 성능 벤치 마크에 비해 측정됩니다. 벤치 마크는 일반적으로 전략이 거래하는 기본 자산 클래스의 큰 샘플을 특성화하는 지수입니다. 전략이 대형 미국 주식을 거래하는 경우 S & P500은 전략을 측정하는 자연스러운 벤치 마크가됩니다. 이 유형의 전략에 적용되는 용어 "알파"및 "베타"가 들립니다. 이 계수에 대해서는 이후 기사에서 자세히 다룰 것입니다.
전략의 실제 수익률에 대해서는 언급하지 않았습니다. 왜 이런거야? 이와는 별도로 수익률은 실제로 전략의 효과에 대한 제한된 정보를 제공합니다. 그들은 레버리지, 변동성, 벤치 마크 또는 자본 요구 사항에 대한 통찰력을주지 못합니다. 따라서 전략은 드물게 자신의 수익만으로 판단됩니다. 수익을보기 전에 항상 전략의 위험 요소를 고려하십시오.
이 단계에서 귀사의 파이프 라인에서 발견되는 많은 전략은 자본 요건, 레버리지 제약, 최대 인출 허용 오차 또는 변동성 선호도를 충족시키지 않기 때문에 거부됩니다. 남아있는 전략은 이제 백 테스트로 간주 될 수 있습니다. 그러나 이것이 가능하기 전에 이러한 전략을 테스트 할 수있는 사용 가능한 과거 데이터의 최종 거부 기준을 고려해야합니다.
내역 데이터 얻기.
요즘에는 과거 데이터 저장을위한 자산 클래스 전반에 걸친 기술적 요구 사항의 폭이 넓습니다. 경쟁 우위를 유지하기 위해 구매자 (펀드)와 매도자 측 (투자 은행) 모두 기술 인프라에 막대한 투자를합니다. 그것의 중요성을 고려하는 것이 필수적입니다. 특히 적시성, 정확성 및 저장 요구 사항에 관심이 있습니다. 이제는 이력 데이터를 얻는 기본 및 저장 방법에 대해 간략하게 설명하겠습니다. 불행히도 이것은 매우 깊고 기술적 인 주제이므로이 기사의 모든 내용을 말할 수는 없습니다. 그러나 필자는 금융 산업에서의 이전 업계 경험이 주로 금융 데이터 수집, 저장 및 액세스에 관심을 가졌으므로 향후이 점에 대해 더 많이 쓰겠습니다.
이전 섹션에서는 우리 자신의 개인 거부 기준에 따라 특정 전략을 거부 할 수있는 전략 파이프 라인을 설정했습니다. 이 섹션에서는 과거 데이터를 얻으려는 우리 자신의 선호도에 따라 더 많은 전략을 필터링 할 것입니다. 주요 고려 사항 (특히 소매 실무자 수준)은 데이터 비용, 저장 요구 사항 및 기술 전문성 수준입니다. 우리는 또한 다양한 유형의 사용 가능한 데이터와 각 유형의 데이터가 우리에게 부과 할 다양한 고려 사항을 논의해야합니다.
사용 가능한 데이터의 유형과 고려해야 할 핵심 쟁점에 대해 논의하겠습니다.
기초 데이터 - 금리, 인플레이션 수치, 기업 활동 (배당, 주식 분할), SEC 신고, 기업 회계, 수익 수치, 작물보고, 기상 데이터 등과 같은 거시 경제 동향에 관한 데이터를 포함합니다. 가치있는 회사 또는 기타 자산을 기초로, 즉 미래의 예상 현금 흐름을 통해 제공해야합니다. 주식 가격 시리즈는 포함되지 않습니다. 일부 기본 데이터는 정부 웹 사이트에서 무료로 사용할 수 있습니다. 다른 장기간의 역사적인 기초 자료는 극도로 비쌀 수 있습니다. 수천 개의 회사가 한 번에 연구되지 않는 한, 스토리지 요구 사항은 대개 크지 않습니다. 뉴스 데이터 - 뉴스 데이터는 본질적으로 정 성적입니다. 기사, 블로그 게시물, 마이크로 블로그 게시물 ( "트윗") 및 사설로 구성됩니다. 감정을 해석하기 위해 분류 자와 같은 기계 학습 기술이 자주 사용됩니다. 이 데이터는 언론 매체를 통한 구독을 통해 종종 무료 또는 저렴한 가격으로 제공됩니다. 새로운 "NoSQL"문서 저장소 데이터베이스는 이러한 유형의 비정형, 정 성적 데이터를 저장하도록 설계되었습니다. 자산 가격 데이터 - 이것은 퀀트의 전통적인 데이터 도메인입니다. 자산 가격의 시계열로 구성됩니다. 주식 (주식), 채권 (채권), 상품 및 환율은 모두이 클래스에 포함됩니다. 주식 등의보다 간단한 자산 클래스를 얻기 위해서는 매일의 과거 데이터가 종종 간단합니다. 그러나 정확성과 청결도가 포함되고 통계 편향이 제거되면 데이터가 비쌀 수 있습니다. 또한 시계열 데이터는 특히 일중 데이터를 고려할 때 중요한 저장소 요구 사항을 가지고 있습니다. 금융 상품 - 주식, 채권, 선물 및 이국적인 파생 상품 옵션은 특성과 매개 변수가 매우 다릅니다. 따라서이를 수용 할 수있는 "한 가지 크기의 모든 것"데이터베이스 구조는 없습니다. 다양한 금융 상품에 대한 데이터베이스 구조의 설계 및 구현에 상당한주의를 기울여야합니다. 우리는 향후 기사에서 유가 증권 마스터 데이터베이스를 구축 할 때 그 상황을 충분히 논의 할 것입니다. 빈도 - 데이터의 빈도가 높을수록 비용 및 저장 요구 사항이 커집니다. 저주파 전략의 경우 일일 데이터로 충분할 수 있습니다. 고 빈도 전략의 경우 틱 수준의 데이터와 특정 거래 교환 주문서 데이터의 기록 사본을 얻는 것이 필요할 수 있습니다. 이러한 유형의 데이터를위한 스토리지 엔진을 구현하는 것은 기술적으로 집중적이며 프로그래밍 / 기술적 배경이 강한 사람들에게만 적합합니다. 벤치 마크 - 위에서 설명한 전략은 종종 벤치 마크와 비교됩니다. 이것은 일반적으로 추가 금융 시간 시리즈로 나타납니다. 주식의 경우 S & P500 지수 (US) 또는 FTSE100 (UK)과 같은 국가 주식 벤치 마크입니다. 고정 수입 기금의 경우 채권 또는 채권 바구니와 비교하는 것이 유용합니다. "무위험 이자율"(즉, 적절한 이자율)은 널리 받아 들여지는 또 다른 벤치 마크입니다. 모든 자산 클래스 카테고리에는 선호되는 벤치 마크가 있으므로 외부 전략에 관심을 가지려면 특정 전략에 따라이를 조사해야합니다. 기술 - 재무 데이터 저장 센터 뒤의 기술 스택은 복잡합니다. 이 기사에서는 건물을 짓는 것과 관련된 것에 대해서만 표면을 긁을 수 있습니다. 그러나 MySQL, SQL Server, Oracle 또는 Document Storage Engine (예 : "NoSQL")과 같은 관계형 데이터베이스 관리 시스템 (RDBMS)과 같은 데이터베이스 엔진을 중심으로합니다. 데이터베이스를 쿼리하고 MATLAB, R 또는 Excel과 같은 외부 도구에 대한 액세스를 제공하는 "비즈니스 로직"응용 프로그램 코드를 통해 액세스 할 수 있습니다. 종종이 비즈니스 로직은 C ++, C #, Java 또는 Python으로 작성됩니다. 또한 개인용 컴퓨터 또는 인터넷 서버를 통해 원격으로이 데이터를 어딘가에 호스팅해야합니다. Amazon Web Services와 같은 제품은 최근 몇 년 동안이 방법을 더 간단하고 저렴하게 만들었지 만 강력한 기술력을 필요로합니다.
위에서 볼 수 있듯이 일단 전략이 파이프 라인을 통해 확인되면 특정 과거 데이터의 가용성, 비용, 복잡성 및 구현 세부 사항을 평가해야합니다. 과거 데이터 고려 사항만을 토대로 전략을 거부 할 필요가 있음을 알 수 있습니다. This is a big area and teams of PhDs work at large funds making sure pricing is accurate and timely. Do not underestimate the difficulties of creating a robust data centre for your backtesting purposes!
I do want to say, however, that many backtesting platforms can provide this data for you automatically - at a cost. Thus it will take much of the implementation pain away from you, and you can concentrate purely on strategy implementation and optimisation. Tools like TradeStation possess this capability. However, my personal view is to implement as much as possible internally and avoid outsourcing parts of the stack to software vendors. I prefer higher frequency strategies due to their more attractive Sharpe ratios, but they are often tightly coupled to the technology stack, where advanced optimisation is critical.
Now that we have discussed the issues surrounding historical data it is time to begin implementing our strategies in a backtesting engine. This will be the subject of other articles, as it is an equally large area of discussion!
양적 거래 시작하기?
QuantStart 목록을 구독해야하는 3 가지 이유 :
1. 퀀트 트레이딩 레슨.
계량 거래를 시작하는 데 도움이되는 힌트와 팁으로 가득한 무료 10 일간 코스에 즉시 액세스 할 수 있습니다!
2. 모든 최신 내용.
매주 나는 퀀트 스타트에서 모든 활동의 포장을 보내드릴 것입니다. 그래서 당신은 결코 다시 글을 놓치지 않을 것입니다.
현실감 넘치는 퀀 트레이딩 팁.

Using SQL Server Data Analysis for Stock Trading Strategies.
By: Rick Dobson | Read Comments (2) | Related Tips: 1 | More > T-SQL.
Our business runs a stock advisory service. Some of our clients trade our recommended stocks at a loss by buying at a high price and selling at a low price. We need some very simple trading models with comparative results to show clients how they can grow the value of their investment accounts with our stock picks.
Data mining - especially the pre-processing, preliminary data analysis, and reporting steps - can be very helpful for addressing your problem. This tip examines six stocks, such as those that might be recommended by your firm, to present the outcome of three different trading strategies. The stock trading strategies are purposely simple so that they can be readily programmed with T-SQL as well as understood by your stock trading clients. All strategies covered are consistent with showing clients how they can grow the value of their investment accounts.
The source data for the tip are stock prices from the Google Finance site. These data are available for free. The tip illustrates how to download stock prices to csv files. Then, the data are transferred to SQL Server tables.
After transferring the stock price data to a SQL Server database, they are pre-processed to make them suitable for examining how each of the three stock trading strategies perform. One stock trading strategy depends on moving averages for stock prices. This tip includes a simple explanation of moving averages as well as an easy way to compute them for stock price data.
The final tip element compares gains and losses from the three the trading strategies. The comparisons are for the six stocks individually and overall. Comparisons are computed on a per share basis as well share lot basis. A share lot is a set of shares for a stock that are bought and sold as a unit.
Downloading the data from the Google Finance site.
You can download historical end-of-day price and volume for a stock from the Google Finance site. Simply enter a URL with parameters, including the stock's symbol as well as the start and end dates for the range of data that you seek. You also need to specify the output format. Your browser, such as Chrome or Internet Explorer, will retrieve the daily stock prices and volumes to a file on your computer.
The following URL specifies the retrieval of historical price and volume data for a stock with the symbol crus. The data starts as of the first trading day on or after January 1, 2008 through to the last trading day for which data are available up until August 31, 2016. The download was taken during the morning on August 24, 2016. The Google Finance site automatically names the downloaded file with the symbol specified in the URL (for example, crus. csv).
Here's a screen shot from Excel showing the first 20 rows of data in the csv file named crus. csv. Notice that there is a separate row for each trading day ending on August 23, 2016, the last trading day for which end-of-day data was available. Aside from the Date column, there are four columns specifying money values (Open, High, Low, Close) and a fifth column shows shares traded on a date for the stock designated by the symbol. While Excel automatically transforms the character data in the crus. csv file to date and numeric values, it is important to keep in mind that the data in the csv file are character data.
Data for six stock symbols were downloaded for this tip. The following bullets show and the symbols along with the corresponding company names and short descriptions. You can see from the descriptions that great diversity is readily available. crus is for Cirrus Logic, Inc. The company supplies circuits for consumer, automotive and professional audio and energy applications edu is for New Oriental Education & Tech Grp (ADR). This symbol represents an ADR for New Oriental Education & Technology Group -- a company operating in China that is a provider of private educational services. An ADR is a stock that trades in the United States but represents a specified number of shares in a foreign corporation meet is for MeetMe, Inc. The company makes available social networks for meeting new people in the US and in Latin America orly is for O'Reilly Automotive Inc, a retailer of automotive parts and accessories stmp is for Stamps, a provider of internet-based mailing and shipping services ulta is for Ulta Salon, Cosmetics & Fragrance, Inc. This firm sells cosmetics, fragrances, skin and hair care products, appliances, and accessories. The company also offers hair salon services and spa treatments.
Migrating the csv files to SQL Server tables.
This tip creates the tables to store the csv file contents in a database named stock_history_data. Then, it populates the SQL Server tables from the downloaded csv files - one table per file. The code provided for the tip will not work as is unless you have the stock_history_data database created on your SQL Server instance. If you do not have the database on your server, running the following script can create the database.
Because the data in the csv files are character-based, you must transform them before you can use them as dates, money, or integers in SQL Server. There are several ways to perform the transformations. A prior tip working with S&P 500 index historical prices (Creating an SSRS Matrix Sparkline Report with Data from Oracle 11g) describes an approach in which the data are imported to SQL Server as character data and then transformed via T-SQL functions to date, money, or integer values. This tip demonstrates how to use built-in SSIS transformation features to convert the data to an appropriate data type.
The following screen shot shows a Control Flow view of the SSIS project for data mining the stock price data downloaded from the Google Finance site. Some annotation text and two steps are highlighted. The highlighted content is for importing the downloaded data into SQL Server.
Additionally, there are 7 connection managers displayed below the control flow area. One is and OLEDB connection manager pointing at the stock_history_data database Six are for flat file connection managers that point at the downloaded csv files.
The following screen shot shows the T-SQL in the create orly ohlcv table Execute SQL Task within the Create stock history ohlcv tables Sequence Container. There are six Execute SQL Task steps in the container - one for each table to receive downloaded data from a csv file. All tables have the same specification except for the symbol name.
When you open a flat file connection manager for the orly. csv file, SSIS automatically sees the UTF-8 character codes sent from the Google Finance site and designates the Microsoft 65001 Code page for reading the character codes. It also expects column headers in the first row, which corresponds to the downloaded format. Therefore, no changes are required to the default General tab that appears below (other than assigning a connection manager name).
This tip uses settings on the Advanced tab to indicate SSIS data types for reading csv file data in a way that is suitable for transferring them to data types in SQL Server tables. Three distinct formats are designated as indicated in the screen shots below. The DT_DBTIMESTAMP data type can read UTF-8 date characters The DT_CY data type can read UTF-8 character fields representing money; this data type designation is appropriate for the Open, High, Low, and Close columns in the csv files The DT_I8 data type can read UTF-8 character fields representing integers that are going to a column with a bigint data type in a SQL Server table.
With the exception of the data for the orly symbol, the csv file contents for the stocks imported successfully to SQL Server tables. However, the data for the orly symbol failed to load successfully on the first try. After examining SSIS logs and the downloaded data in Notepad++, it was discovered that selected columns in the orly data for three dates (November 24, 2010, December 23, 2010, and December 29, 2010) were incorrectly specified.
See the screen below to view from Notepad++ the faulty data in the orly. csv file. Notice that the bad data were for the Open, High, and Low columns. The data for the Date and Close column values appeared valid, but the data for the Volume column did not appear valid. However, this tip only requires valid, correct Date and Close column values.
It was the bad data for the Open, High, and Low columns that caused the importing of the orly. csv file data to fail initially. You can bypass the failure by configuring settings within the Flat File Source for the orly csv step to assign NULL values to columns with invalid data during the import process. The following screen shot shows the Ignore failure settings for the Open, High, and Low columns in the orly. csv file. With these configuration changes in the Error Output tab of the Flat File Source for orly csv step, it was possible to load the orly. csv file along with downloaded data for the other five symbols.
Pre-processing the imported data for trading strategy evaluations.
Up to this point, the imported data exists in six separate tables with dates going back to the first trading date in 2008 or whenever the Google Finance site first started reporting stock prices for a symbol. Aside from variations in the start date for different symbols, I sometimes noticed dates with rows of data for one symbol that were missing for other symbols. For the six stock symbols used in this tip, these missing dates were very rare and limited to data prior to 2011. The missing data are not relevant to this tip because stock trading rules were compared only for trading strategies in the 25-month window from July 2014 through July 2016.
In addition, to pre-processing filters for the date range, other pre-processing was implemented. Data were consolidated from six separate tables without a symbol indicator into one table with a distinct symbol indicator for each stock. This step makes it easier to evaluate trading strategies across all six stocks Also, 10-day and 30-day moving averages were computed from the base stock price data. Moving averages are a common technical analysis tool for analyzing stock trends. The 10-day moving average reflects short-term trends, and the 30-day moving average reflects longer-term trends.
The following T-SQL script shows code for selecting data from the crus table, adding a symbol column, and computing 10-day and 30-day moving averages. This link compares 6 different methods for computing a sum over a rolling window, such as 10 days or 30 days. The method with the best performance used a customized version of the SUM function that depended on PRECEDING and CURRENT ROW key words. The following code illustrates an adaptation of the best method for computing moving averages instead of sums over a rolling window.
The following screen shot displays an excerpt from the result set for the preceding script. The mav_10 column shows 10-day moving average values and the mav_30 column reveals 30-day moving average values. Notice that values for these columns do not start until the tenth and thirtieth rows, respectively. This is because a 10-day moving average requires at least 10 preceding days of values, and a 30-day moving average requires at least 30 days of preceding values. Rolling windows determine which dates contribute to the moving average values on each row.
The step named create stocks_ohlcv_with_mav_10_30 table with consolidated stock histories and add mav_10 and mav_30 in the Control Flow diagram displayed in the second screen shot within this tip includes the complete script for date filtering, consolidation, adding symbols, and computing moving averages. The step stores its outcome in the stocks_ohlcv_with_mav_10_30 table.
There are 525 stock trading days from July 2014 through July 2016. For the six stocks examined within this tip, this means there are 3150 rows in the stocks_ohlcv_with_mav_10_30 table. The following screen shot shows the first 31 rows in the table. Because the data are arranged by Date within Symbol, these rows are for the earliest 31 trading days for the crus symbol. Because the moving averages are computed on values going back as far as 2008, there are no NULL values for either the 10-day or 30-day moving averages.
Three trading rules.
Before moving to the final pre-processing step for the stock price data, it will be helpful to review the three trading strategies evaluated in this tip. Recall that the objective is to evaluate simple trading rules because we want the rules to be easily understood by clients of the stock advisory service. Also, we seek rules which are safe to trade - so that stock price gains go up if stock prices rise throughout an evaluation period (we'll site a couple of examples where a trade can lose money even while a stock price is rising over an extended period). This tip evaluates trading strategies for the 25-month period from July 2014 through July 2016. Additionally, we need rules that can be readily compared to one another. The rules examined in this tip are more like benchmarks for contrasting trading styles than precise recommendations on how to trade stocks.
The three trading rules evaluated by this tip are as follow. The overall buy-and-hold rule buys shares for a stock at the Open price of the first trading day in July 2014 and sells those shares at the Close price on the last trading day in July 2016 The monthly buy-and-hold rule buys shares for a stock at the Open price for each month from July 2014 through July 2016. On the last trading day of each month, the rule sells the stocks purchased at the beginning of the month The conditional buy-and-hold strategy buys shares for a stock only when the short-term price trend at the beginning of month as indicated by the 10-day moving average is greater than the long-term trend as indicated by the 30-day moving average. Otherwise, no purchase is made for a stock during the month. To keep the code simple for this trading rule comparison, we assume that you know the 10-day and 30-day moving average values for the month's first trading day at the start of a month's first day.
Trading plans are compared on a share price change as well as a lot price change basis. Share price change is computed based on the difference between the Open price on first trade for a period versus the Close price on the last day of a period. If the Close price is greater than the Open price, then rule results in a gain. Otherwise, the rule breaks even or loses money The start and end days change from one rule to the next For the buy-and-hold rule, there is just one start date and one end date. The start date is the first trading day at the beginning of July 2014. The end date is the last trading day of July 2016 For the monthly buy-and-hold rule, there is start date and end date for each of the 25 months from July 2014 through July 2016. Within each month, the start date is always the first trading day of the month, and the end date is always the last trading day of the month For the conditional buy-and-hold rule, there are a variable number of months in which stocks can be bought and sold. Stocks are only bought on months when the 10-day moving average is greater than the 30-day moving average at the beginning of the month. If there is a stock purchase at the start of a month with this rule, then the close price is for the last trading day in the month Recall that the term lot refers to the collection of stock shares bought during a trade. The term lot size indicates the number of stock shares bought at one time. For evaluation in the context of this tip, the lot size for the monthly buy-and hold rule is the number of shares purchased (rounded up to the nearest 10 shares) so the average monthly price is $4,000 or slightly more. The lot size varies from one stock to the next within a month. The lot sizes computed for the monthly buy-and-hold rule are also used for the conditional buy-and-hold rule The overall buy-and-hold rule uses the monthly buy-and-hold lot size of July 2014 for its first buy. Because at the end of 25 months you sell the shares acquired in the initial purchase with the overall buy-and-hold rule, the lot size sold in July 2016 is the same as the shares bought in July 2014 The conditional buy-and-hold rule uses the monthly buy-and-hold lot sizes. The only difference is that for months in which the initial 10-day moving average is less than or equal to the initial 30-day moving average, there is no buying and selling of stock.
The table for evaluating trading rules.
This tip uses the data_for_trading_rules table to store data in a format that simplifies the computation of gains and losses on a monthly basis. The next screen shot shows the first 25 rows of the data_for_trading_rules table. Notice that all 25 rows are for the crus symbol. The first three columns denote the symbol and time period for the rest of the data on a row The first_day and last_day columns are not strictly necessary, but they provide a way of visually confirming these dates are within the year and month for the row The Open column indicates the open price on the first trading day of the month for the row The mav_10_first_day and mav_30_day columns display the 10-day and 30-day moving average on the first trading day of the month The Close column reveals the closing price on the last trading day of the month.
All the data that you need for evaluating the monthly and conditional buy-and-hold trading rules is on one row of the data_for_trading_rules table. For example, the Close column value less the Open column value indicates the gain or loss per share for the month with the monthly buy-and-hold rule. The conditional buy-and-hold rule only uses the difference between the Close and Open column values for months in which the 10-day moving average is greater than the 30-day moving average. By summing the gain or loss for each month in which there was a trade, you can derive the gain or loss across all 25 months for which stock prices are tracked.
For the overall buy-and-hold rule, you need two rows from the data_for_trading_rules table to evaluate the gain or loss for the trading rule. The difference between the Close price for July 2016 less the Open price for July 2014 returns the gain or loss for a stock. Just as with the monthly rules, you compute this value separately for each stock.
The following script shows the T-SQL script for computing the data_for_trading_rules table. The script contains two derived table queries. The first_day_data derived table query returns the Open price along with the 10-day and 30-day moving averages for the first trading day of each month The last_day_data derived table query returns the Close price for the last trading day of each month A sub-query within the first_day_data and last_day_data derived table queries allows the queries to return data for just the first or last day in a month from the stocks_ohlcv_with_mav_10_30 table The two derived table queries are inner joined based on SYMBOL, YEAR, and MONTH to put opening and closing prices on the same row of the data_for_trading_rules table The INTO clause just before the FROM clause in the main outer query populates the data_for_trading_rules table.
Evaluating the Trading Rules.
Three SSRS reports are provided as a model for evaluating the trading rules with the six stocks examined in this tip. The summary results do not include trading costs because commissions per trade can vary (or even be zero in some cases) depending on the broker and security in which you invest. However, if you plan on using a particular broker with a standard fee per trade, you may want to factor in a broker commission.
The first report is a top line report comparing the three trading strategies for gain versus loss on a per share basis and a lot size basis. As the screen shot below shows, all three trading strategies generated gains over the 25-month evaluation period for each of the stocks and overall. The buy-and-hold strategy edged out the buy-and-sell every month rule (overall gain of $22,964 for buy-and-hold versus $22,950 for buy-and-sell every month). The trading strategy based on the 10-day moving average versus the 30-day moving average generated the smallest gains by a substantial margin. We show why this outcome is obtained in the next couple of reports.
As you can see, there are 8 columns in the body of the top-line report. The query for the report starts with a SELECT statement that references two main derived table queries -- each of which has its own sub-queries. The listing below just shows the outer most query and references to the main derived table queries so you are not distracted by details from getting the big picture about how the report compiles data. If you wish, you can examine the complete query for the top line comparison of trading strategies report in the SSRS project available for download with this tip. One main derived query generates summary data for the buy and hold strategy; its name is buy_and_hold_summary The other main derived table query generates summary results for the monthly buy and hold rule versus the conditional buy-and-hold rule based on moving averages.
The next screen shot presents another report with detailed results for the monthly buy-and-hold trading rule. You can use this report to examine results for any of the six stocks in the data set for this tip. The screen shot below shows results for the stock with the crus symbol.
This second report displays monthly trading gain-loss outcomes on a per share basis and a lot size basis for the symbol entered into the SYMBOL selection box. Months with a loss show their outcome in red; otherwise, the per share and per lot size outcome shows in green.
Although the preceding report shows that the gain for the crus stock was about $3,780, the following report shows a loss in 10 of the 25 months for which price data was analyzed. Furthermore, the stock loses value in 4 of the first 5 months and an additional span of three consecutive months (June 2015 through August 2015) that were analyzed. If a client invested in the crus stock exclusively during either of these periods, they could easily conclude a recommendation for crus was a bad one in spite of the fact that the stock gained over 100% over the 25-month evaluation period!
The following query shows the code for reporting monthly buy-and-hold trade outcomes. The outermost SELECT statement references two derived table queries that are inner joined. The outermost SELECT computes one result (G/L for lot size) and renames other columns from their underlying source. Also, the SYMBOL parameter in the code's last line allows the report user to specify a stock symbol for which to show results. The monthly_G/L_per_share derived table query returns for each month the difference between the final closing price and the initial opening price; this is the gain or loss per share for a month The shares_to_buy_sell derived table query computes the lot size for a stock, which is, in turn, used by the outermost query to help generate the gain or loss per lot for a month.
The next screen shot for this tip shows the trading outcomes when the 10-day moving average is greater than the 30-day moving average at the start of the month. The result of the rule is that trades are not made in 10 months for which the every-month rule makes a trade. Both this report and the preceding one are for the stock with a crus symbol.
There are 10 months in which the trading rule based on moving averages skips a trade for a month relative to the every-month trading rule. The trading rule based on moving averages skipped 5 losses and 1 no-change outcome. These good results from the moving average rule are counter-balanced, in part, by missed gains in 4 months. The top-line report above shows that the moving average returned over $700 less gains than the every-month rule for the crus stock. The shrinkage in gains was even greater for the remaining 5 stocks.
My take-away from these results is that the moving average rule is not sufficiently accurate about discovering when a month is likely to result in a loss versus a gain. For example, if the moving average rule was 100% accurate, trading would occur only for months in which there was a gain. More research to discover better trading rules for avoiding losses while not missing gains might result in selective trading strategies that are better than buy-and-hold or buy-and-sell every month.
The following script shows the query for the report on the moving average trading rule. This script differs from the script for the every-month rule in that it shows 10-day and 30-day moving averages and that it only presents trading outcomes for months where the initial 10-day moving average is greater than the initial 30-day moving average.
다음 단계.
This tip presents three simple trading models implemented via T-SQL code for a selection of 6 stocks over a 25-month evaluation period. Three SSRS reports are also presented for contrasting and analyzing the trading models. The reports show that it is possible to have stocks that gain significant value over the 25-month evaluation even when selectively investing in the stocks for just some months can actually generate a loss. By sharing these results with its clients, the stock advisory firm can help clients avoid losing money on poorly timed stock trades for recommended stocks. Because all steps from downloading historical stock prices through to preparing the reports are described, the stock advisory firm can use any other set of stocks besides those covered in this tip for a report to its clients. Also, any evaluation period for which the Google Finance site has stock prices can be used for reporting the results of trading rules. Finally, additional data mining of stock price data may lead to better rules for extracting more gains from stock trading. The resource files folder for this tip include the project files for the SSIS and SSRS projects mentioned in the tip along with other scripts that you may find useful. Please be sure and review the readme. txt file in the resource solution folder before trying to reproduce any results in the tip based on the files in the resource files folder. Finally, I close by indicating that this tip is not recommending any particular stocks, including the six analyzed ones. These stocks were chosen because I had been watching them as part of my normal investing due diligence. At the time that I submitted this tip to MSSQLTips, I held positions in three stocks among the six in the tip.
저자에 대해서.
감사. I enjoyed writing the tip.
정말 멋진. 게시 해 주셔서 감사합니다.
Learning.
수색.
더 많은 정보.
Copyright (c) 2006-2017 Edgewood Solutions, LLC All rights reserved.
Some names and products listed are the registered trademarks of their respective owners.

No comments:

Post a Comment