Tuesday 13 March 2018

R 크레인 외환


R 크레인 외환
이 CRAN 작업보기에는 주제별로 그룹화 된 재무 실증 분석에 유용한 패키지 목록이 포함되어 있습니다.
이러한 패키지 외에도 재무에서의 경험 작업에 적합한 매우 다양한 기능이 기본 R 시스템 (및 권장되는 핵심 패키지 세트)과 포괄적 인 R 아카이브 네트워크 (CRAN)의 여러 패키지에서 제공됩니다. 결과적으로 다른 CRAN 작업 뷰 중 몇 가지는 적합한 계량 분석, 특히 계량 경제학, 다 변수, 최적화, 강인성, 사회 과학 및 TimeSeries 작업 뷰를 포함 할 수 있습니다.
ctv 패키지는 이러한 작업보기를 지원합니다. 이 함수의 기능 install. views와 update. views는 각각 주어진 Task View의 패키지 설치 또는 업데이트를 허용한다. coreOnly 옵션은 아래 코어로 레이블이 지정된 패키지로 작업을 제한 할 수 있습니다.
기고는 언제나 환영 받고 고무되어 있습니다. 2005 년 4 월이 CRAN 작업보기가 시작된 이래로 대부분의 기고가 제안으로 도착했습니다. 이 특정 작업보기 파일의 소스 파일도 GitHub 저장소 (아래 참조)에 있으므로 끌어 오기 요청도 가능합니다.
표준 회귀 모델.
사용 가능한 회귀 방법론에 대한 자세한 개요는 계량 경제학 작업보기에서 제공됩니다. 이는보다 강력하고 내성이 강한 방법에 중점을 둔 강력한 작업보기로 보완됩니다. 정규 최소 제곱 (OLS)과 같은 선형 모델은 lm () (기본 R 분포에 포함 된 통계 패키지에서 제공)에서 추정 할 수 있습니다. ML (maximum likelihood) 추정은 표준 optim () 함수를 사용하여 수행 할 수 있습니다. 다른 많은 적합한 방법이 최적화보기에 나열되어 있습니다. 비선형 최소 제곱은 nls () 함수뿐만 아니라 nlme 패키지의 nlme () 함수를 사용하여 추정 할 수 있습니다. 선형 모델의 경우 다양한 회귀 진단 테스트가 car, lmtest, strucchange, urca 및 샌드위치 패키지로 제공됩니다. Rcmdr 및 Zelig 패키지는 관심의 대상이 될 수있는 사용자 인터페이스를 제공합니다.
시계열 분석 도구에 대한 자세한 개요는 TimeSeries 작업보기에서 확인할 수 있습니다. 다음은 금융에서 가장 중요한 방법에 대한 간략한 개요입니다. 고전적인 시계열 기능은 기본 R 배포판의 arima () 및 KalmanLike () 명령에 의해 제공됩니다. dse 및 timsac 패키지는 다양한 고급 추정 방법을 제공합니다. fracdiff는 부분적으로 통합 된 계열을 추정 할 수 있습니다. longmemo는 관련 자료를 다룹니다. 프랙탈은 프랙탈 시계열 모델링 기능을 제공합니다. 변동성 모델링의 경우, 표준 GARCH (1,1) 모델은 tseries 패키지에서 garch () 함수로 추정 할 수 있습니다. Rmetrics (아래 참조)에는 추가 모델이있는 fGarch 패키지가 포함되어 있습니다. rugarch 패키지는 ARFIMA, 평균값, 외부 회귀 변수 및 기타 다양한 사양과 같은 확장을 사용하여 다양한 단 변수 GARCH 모델을 모델링하는 데 사용할 수 있습니다. 예측, 시뮬레이션, 추론 및 플로팅 방법도 제공됩니다. rmgarch는 여러 다 변수 GARCH 모델을 추정 할 수있는 기능을 제공합니다. betategarch 패키지는 Harvey가 Beta-t-EGARCH 모델을 평가하고 시뮬레이션 할 수 있습니다. bayesGARCH 패키지는 학생의 혁신으로 GARCH (1,1) 모델의 베이지안 추정을 수행 할 수 있습니다. 다 변수 모델의 경우 ccgarch 패키지는 조건부 상관 관계 GARCH 모델을 (다 변수) 추정 할 수 있지만 gogarch 패키지는 일반화 된 직교 GARCH 모델에 대한 함수를 제공합니다. 도착 패키지 (AutoSEARCH와 관련된 패키지가 앞에 있음)는 log-ARCH-X 모델의 평균 및 로그 변동성에 대한 자동화 된 일반 모델을 선택합니다. GEVStableGarch 패키지는 GEV 및 안정적인 조건부 배포가있는 ARMA-GARCH 또는 ARMA-APARCH 모델에 적합합니다. lgarch 패키지는 log-Garch 모델을 평가하고 적합시킬 수 있습니다. 단위 근원과 공적분 검정은 tseries와 urca에 의해 제공된다. Rmetrics 패키지 timeSeries 및 fMultivar에는 ARMA, GARCH, 긴 메모리 모델, 단위근 및 기타에 대한 많은 평가 함수가 포함되어 있습니다. CADFtest 패키지는 Hansen 단위 루트 테스트를 구현합니다. MSBVAR은 벡터 자동 회귀 모델의 베이지안 추정을 제공합니다. dlm 패키지는 동적 선형 모델 (예 : 선형 가우스 상태 공간 모델)의 베이지안 및 가능성 분석을 제공합니다. vars 패키지는 고전적인 프레임 워크에서 VAR 및 SVAR 모델의 추정, 진단, 예측 및 오류 분해를 제공합니다. dyn 및 dynlm 패키지는 동적 (선형) 회귀 모델에 적합합니다. 여러 패키지는 웨이브 렛 분석 기능을 제공합니다 : rwt, 웨이브 렛, 웨이브 림, 웨이브 시트. 혼돈 이론의 일부 방법은 tseriesChaos 패키지에 의해 제공됩니다. tsDyn은 동적 시스템 이론을 기반으로 시계열 분석을 추가합니다. 예측 패키지는 문제를 예측하는 기능을 추가합니다. tsfa 패키지는 시계열 분석을위한 함수를 제공합니다. stochvol 패키지는 Markov Chain Monte Carlo를 사용하여 확률 적 변동성에 대한 Bayesian 추정을 구현하고 factorstochvol은이를 다 변수 케이스로 확장합니다. MSGARCH 패키지는 (Maximum Likelihood 또는 Bayesian에 따라) 다양한 Markov-Switching GARCH 프로세스를 시뮬레이션하고 예측하는 방법을 추가합니다.
Rmetrics 패키지 패키지는 fAssets, fBasics, fBonds, timeDate (이전 : fCalendar), fCopulae, fCopulae, fExoticOptions, fExtremes, fGarch, fImport, fNonlinear, fOptions, fPortfolio, fRegression, timeSeries (이전 : fSeries), fTrading 경험적 및 전산 금융의 다양한 측면에 대한 많은 관련 기능. RQuantLib 패키지는 몇 가지 옵션 가격 책정 기능과 QuantLib 프로젝트에서 R에 이르는 일부 고정 수입 기능을 제공합니다. RcppQuantuccia는 QuantLib 기능의 하위 집합을 헤더 전용 라이브러리로 제공합니다. 현재 일부 캘린더 기능 만 노출됩니다. quantmod 패키지는 데이터 수집, 플로팅 및 기타 유틸리티뿐만 아니라 재무에서의 정량 모델링을위한 많은 기능을 제공합니다. 포트폴리오 패키지에는 주식 포트폴리오 관리 클래스가 포함되어 있습니다. portfolioSim은 관련 시뮬레이션 프레임 워크를 구축합니다. 백 테스트는 금융 상품에 대한 포트폴리오 기반 가설을 탐색 할 수있는 도구를 제공합니다. PA 패키지는 주식 포트폴리오에 대한 성과 기여 기능을 제공합니다. PerformanceAnalytics 패키지에는 포트폴리오 성과 계산 및 위험 관리를위한 많은 기능이 포함되어 있습니다. TTR은 R에서 기술 거래 규칙을 구성하는 기능을 포함합니다. 금융 패키지는 현재 가치, 현금 흐름 및 기타 간단한 재무 계산을 계산할 수 있습니다. sde 패키지는 확률 미분 방정식에 대한 시뮬레이션 및 추론 기능을 제공합니다. termstrc 및 YieldCurve 패키지에는 Svensson (1994) 확장을 사용한 매개 변수 Nelson and Siegel (1987) 방법을 기반으로 제로 쿠폰 수익률 곡선 및 스프레드 곡선을 추정하는 방법이 포함되어 있습니다. 이전 패키지에는 McCulloch (1975) 3 차 스플라인 접근법이 추가되었으며, 후자의 패키지에는 Diebold 및 Li 접근법이 추가되었습니다. SmithWilsonYieldCurve는 LIBOR 및 SWAP 비율을 기반으로 한 Smith-Wilson 방식을 사용하여 수익률 곡선을 만듭니다. vrtest 패키지에는 효율적인 시장 가설의 약자 형태에 대한 다양한 분산 비율 테스트가 포함되어 있습니다. gmm 패키지는 자산 가격 결정 모델에 의해 암시되는 순간 조건의 매개 변수를 추정 할 때 자주 사용되는 일반화 된 GMM 추정 함수를 제공합니다. tawny 패키지는 샘플 공분산 행렬을 추정 할 때 샘플링 잡음을 제거하는 축소 방법뿐만 아니라 무작위 행렬 이론을 기반으로 한 견적기를 포함합니다. opefimor 패키지에는 Iacus (2011) 책 "옵션 가격 결정 및 R의 재무 모델 추정"과 함께 제공되는 자료가 포함되어 있습니다. maRketSim 패키지는 채권 시장을 중심으로 설계된 시장 시뮬레이터를 제공합니다. BurStFin 및 BurStMisc 패키지에는 공분산 행렬의 추정을 포함하여 Finance의 기능 모음이 있습니다. AmericanCallOpt 패키지에는 다양한 미국 통화 옵션에 대한 가격이 포함되어 있습니다. VarSwapPrice 패키지는 유럽 옵션 계약 포트폴리오를 통해 변동 스왑 가격을 책정 할 수 있습니다. FinAsym 패키지는 Lee와 Ready (1991) 및 Easley and O'Hara (1987) 테스트를 각각 무역 방향과 정보에 입각 한 거래 확률로 구현합니다. parma 패키지는 포트폴리오 할당 및 위험 관리 응용 프로그램을 지원합니다. GUIDE 패키지는 DE 경쟁자를위한 GUI를 제공하며 이러한 가격 책정 기능을 연구하기위한 대화 형 2 차원 및 3 차원 플롯과 함께 수많은 비싼 예제를 포함합니다. SharpeR 패키지에는 Sharpe 비율과 overfit을 기반으로 거래 전략의 중요성을 분석하기위한 도구 모음이 포함되어 있습니다. RND 패키지는 옵션 가격으로부터 위험 중립적 인 밀도를 추출하는 다양한 기능을 구현합니다. LSMonteCarlo 패키지는 Least Squares Monte Carlo 방법을 통해 American Options 가격을 책정 할 수 있습니다. BenfordTests 패키지는 수치 데이터가 Benford의 법칙에 부합하는지 여부를 결정하기위한 7 가지 통계 테스트 및 지원 기능을 제공합니다. OptHedging 패키지는 옵션 포트폴리오를 호출하고 최적의 헤징 전략을 구현합니다. markovchain 패키지는 개별 마르코프 체인을 쉽게 처리하고 분석 할 수있는 기능을 제공합니다. ycinterextra 패키지 모델은 Hermite 3 차 스플라인뿐 아니라 Nelson-Siegel, Svensson 또는 Smith-Wilson 모델을 통해 곡선 보간 및 외삽을 생성합니다. tvm 패키지 모델은 현금 흐름 및 수익률 곡선과 같은 시간 가치 현금 기능을 제공합니다. MarkowitzR 패키지는 Markowitz 포트폴리오의 통계적 중요성을 테스트하는 기능을 제공합니다. pbo 패키지는 거래 전략을 분석 할 때 역 테지 오버 피팅 가능성, 성능 저하, 손실 확률 및 확률 적 우위를 모델링합니다. OptionPricing 패키지는 Geometric Brownian Motion에서 아시아 및 유럽 옵션의 가격 및 민감도에 대해 효율적인 Monte Carlo 알고리즘을 구현합니다. matchingMarkets 패키지는 내재적 매칭 (예 : 소액 금융의 그룹 형성 또는 기업과 벤처 자본가의 매칭)에서 발생하는 편향성을 수정하기위한 구조 추정을 구현합니다. restimizeapi 패키지는 군중 - 소스 수입 추정치를 제공하는 견적시 API에 인터페이스합니다. 크레디트 패키지는 신용 디폴트 스왑에 대한 또 다른 가격입니다. covmat 패키지는 공분산 행렬을 계산하기위한 여러 가지 다른 방법을 제공합니다. ObAnalytics 패키지는 제한 주문서 데이터의 이벤트 정보를 분석하고 시각화합니다. derivmkts 패키지는 파생 상품 시장을 가르치는 데 유용한 가격 책정 및 설명 기능 세트를 추가합니다. PortfolioEffectHFT 패키지는 일일 및 고주파 데이터에 적합한 포트폴리오 분석을 제공하고 PortfolioEffect 서비스에도 인터페이스합니다. 블랙 & 숄즈 (Black and Scholes)의 연장에 따른 ragtop 패키지의 주식 파생 상품 가격은 지수 관련 링크 가격과 위험 비율로 불이행을지지합니다. sharpeRratio 패키지는 Sharpe 비율에 대한 순간적인 추측을 추가합니다. QuantTools 패키지는 향상된 양적 거래 및 모델링 도구를 제공합니다. pinbasic 패키지는 Easley 등이 제공 한 Informed Trading (PIN)의 확률을 빠르고 안정적으로 추정하기위한 도구를 추가하고 모델 가능성을 인수 분해합니다. InfoTrad 패키지는 또한 PIN을 추정하고 다양한 인수 분해 및 추정 알고리즘을 확장합니다. FinancialMath 패키지에는 보험 계리사 및 사상자 계리 학회의 '금융 수학'시험 학회의 보험 계리 시험에서 요구하는 금융 수학 및 파생 상품 가격 결정 기능이 포함되어 있습니다. tidyquant 패키지는 소위 tidyverse에서 사용하기 위해 몇 가지 다른 주요 패키지의 기능을 재정렬합니다. BCC1997은 확률 적 변동성, 확률 적 속도 및 무작위 점프에 대한 Bakshi, Cao anc Chen (1997) 모델 하에서 유럽의 옵션을 제시한다. Sim. DiffProc 패키지는 연속 시간 모델에 대한 다차원 It ґ 및 Stratonovitch 추계 미적분을 시뮬레이션하고 분석하는 함수를 제공합니다. rpgm 패키지는 정상 및 지수 무작위 변수 및 확률 미분 방정식의 빠른 시뮬레이션을 제공합니다. BLModel 패키지는 자산 반환과 외부 함수에 의해 주어진 뷰의 연속적인 분포에 의해 주어진 사전 분포로부터 Black-Litterman 모델에서 사후 분포를 계산합니다. rpatrec 패키지는 (재정적) 시계열 데이터의 차트 패턴을 인식하는 것을 목표로합니다. PortfolioOptim은 작고 큰 샘플 포트폴리오 최적화를 모두 해결할 수 있습니다.
ExtremeValue 작업보기는 많은 관련 패키지를 재 그룹화합니다. CreditMetrics 및 crp. CSFP 패키지는 신용 위험을 모델링하는 기능을 제공합니다. mvtnorm 패키지는 다 변수 일반 및 t - 분포에 대한 코드를 제공합니다. Rmetrics 패키지 fPortfolio 및 fExtremes에는 여러 가지 관련 기능이 포함되어 있습니다. copula와 fgac 패키지는 copula 메소드를 사용하여 다변량 종속 구조를 다룹니다. 보험 패키지는 리스크 관리에 대한 보험 수리적 관점을 제공합니다. ghyp 패키지는 VaR, CVaR 또는 대상 반환 포트폴리오 최적화 절차뿐만 아니라 일반화 된 hyberbolic 배포 기능을 제공합니다. ChainLadder 패키지는 보험금 준비금을 모델링하는 기능을 제공합니다. 생명 보장 패키지는 생명의 우연성에 대한 재정적 및 보험 통계적 평가를위한 기능을 제공합니다. frmqa 패키지는 재무 위험 관리 및 정량 분석 ​​기능을 수집하는 것을 목표로합니다. ESG 패키지는 자산 투영 (시나리오 기반 시뮬레이션 접근법)을 모델링하는 데 사용할 수 있습니다. riskSimul 패키지는 로그 반환이 일반화 된 쌍곡선 또는 t 마진을 갖는 t-copula 모델을 따르는 주식 포트폴리오에 대한 꼬리 손실 확률 및 조건부 초과를 추정하기위한 효율적인 시뮬레이션 절차를 제공합니다. GCPM 패키지는 분석 및 시뮬레이션 접근법을 사용하여 신용 포트폴리오의 기본 위험을 분석합니다. FatTailsR 패키지는 대칭 및 비대칭 지방 꼬리가있는 배포판에 적합한 4 가지 배포판 제품군을 제공합니다. Dowd 패키지에는 Kevin Dowd의 저서 "Measuring Market Risk"에서 제공하는 'MMR2'도구 상자에서 이식 된 함수가 포함되어 있습니다. PortRisk 패키지는 포트폴리오 위험 기여도를 계산합니다. NetworkRiskMeasures 패키지는 DebtRank, Impact Susceptibility, Impact Diffusion 및 Impact Fluidity와 같은 금융 네트워크에 대한 몇 가지 위험 측정을 구현합니다.
NMOF 패키지는 Differential Evolution, Genetic Algorithms, Particle Swarms 및 Threshold Accepting과 같은 다양한 최적화 휴리스틱을 포함하여 Manfred Gilli, Dietmar Maringer 및 Enrico Schumann (2011)의 Numerical Methods and Finance에서 제공하는 함수, 예제 및 데이터를 제공합니다. FRAPO 패키지는 Bernhard Pfaff (2013)가 작성한 재무 위험 모델링 및 포트폴리오 최적화에 대한 데이터 세트 및 코드를 제공합니다.

기계적인 Forex.
기계 거래 전략을 사용하여 외환 시장에서 거래합니다.
알고리즘 거래에서 R 사용 : 간단한 시계열 특성 분석. 1 부.
지난 주 우리는 IS / OS 시스템 특성 배열을 분석하고 IS / OS 내역 상관 관계에 대한 간단한 결론을 도출하기 위해 R 통계 패키지를 사용했습니다. 오늘날 우리는 R을 사용하여 시스템 생성 전에 수행되어야하는보다 근본적인 분석을 수행하려고합니다. 이 분석은 금융 시계열의 기본 특성에 해당합니다. 이는 우리가 거래 할 기호에 대한 근본적인 정보를 제공합니다. 이 분석을 통해 우리는 전통적인 알파 탐색 알고리즘 전략을 개발하는 것이 더 쉬울 수있는 곳과 특정 기호 내에서 (근본적인 장기 바이어스와 같은) 일부 항목이 존재하는지 여부를 파악할 수 있습니다. 이 첫 번째 튜토리얼에서는 금융 시계열에 대한 몇 가지 기본적인 통계 특성을 다룰 것입니다. 실종 된 유용한 특성이있는 경우 관측과 함께 의견을 게시하십시오 (필자는 분명히 다음 몇 부분에 포함 할 것입니다).
무엇보다도 우리는 우리의 데이터가 R에 친숙한 CSV 파일에 포함되어 있는지 확인해야합니다. 열기 / 높음 / 낮음 / 닫음 열뿐만 아니라 날짜 열에 촛불 사용 시간이 적절한 형식으로 포함되어야합니다. R (예 : 1986-03-23). R에는 적절한 열 머리글이 있어야하므로 csv의 첫 번째 줄에는 날짜, 열기, 높음, 낮음, 닫기와 같은 내용을 읽어야합니다. 이 시리즈의 다음 몇 게시물에서이 퀵 모드 (예 : quantmod)가 필요한 다른 라이브러리를 사용할 때 데이터를 이렇게 형식화해야합니다 (Hurst 지수와 같은 고급 분석을 수행 할 때). 견적). 기본적인 통계 계산을 위해 필요할 것이므로 계속하기 전에 e1071 R 라이브러리도 설치했는지 확인하십시오. 데이터를 준비하고 나면 이제 R에로드하고 제대로로드되었는지 확인하기 위해 플롯 할 수 있습니다 (quantmod를 사용할 때 더 예쁜 촛대 차트를 그릴 수있는 방법을 배웁니다.
데이터가로드되면 Open / High / Low / Close 데이터를 직접 비교할 수 없기 때문에 여러 심볼간에 비교할 수있는 통계량을 갖기 위해 가격 시리즈의 수익률을 계산할 수 있습니다. 백분율 리턴은 단순히 100 * (Close [n] - Close [n-1] / Close [n-1])로 주어지며, 간격 재생 때문에 Close [n] - Open [n] 차이를 사용하지 않습니다 특정 도구를 통해 매우 중요한 역할을하므로 계산시이를 고려해야합니다. 또한 log (Close [n]) 기반의 수익률은 대부분의 금융 시계열에서 정규 분포에 가까운 결과를 제공하기 때문에 일반적으로 사용됩니다. 어떤 것을 사용할지는 주로 분석이 정규성을 가정해야하는지 여부에 달려 있습니다. 이 자습서에서는 표준 백분율을 사용하려고합니다. 사용할 수있는 다양한 반환 유형에 대한 자세한 내용은이 링크를 확인하십시오. 반환 값을 계산하려면 몇 가지 추가 R 명령을 실행해야합니다.
먼저 배열에 차등을 채운 다음 이전 닫기 값을 기반으로 올바른 정규화 된 차이로 다시 채우는 방법으로 수익을 계산했습니다. R에서 이것을 할 수있는 더 좋은 방법이있을 것입니다. (아는 한 주석을 달아주세요!)하지만 C ++의 정신력을 사용하여 간단히 말했습니다.) 이제 시계열에 대한 흥미로운 통계를 보여주는 몇 가지 추가 계산을 수행 할 수 있습니다. 우리는 평균, Â 왜곡, κ 첨도 및 우리의 수익에 대한 연속 자기 상관을 계산할 수 있습니다. 비대칭은 분포가 음수 또는 양수 값으로 기울어 졌는지를 말해줍니다 (완벽하게 대칭 인 확률 분포는 0을 나타냅니다). 반면에 kurtosis는 우리의 분포가 얼마나 뚱뚱한 (높은 kurtosis) 또는 매우 정점 (낮은 kurtosis)인지를 알려줍니다 정상 분포. 높은 첨도 (kurtosis)는 배포본의 편차가 극단적 인 편차로 인해 발생할 가능성이 높다는 것을 의미합니다. 또한 이러한 유사 콘텐츠를 더 잘 볼 수 있도록 히스토그램을 얻을 수 있습니다.
위에서 볼 수 있듯이 EUR / USD의 수익률은 정규 분포에서 크게 벗어나며 (향후 게시물에 대한 정상 테스트에서 더 많음) 이미 EUR / USD 분포의 일부 특성을 볼 수 있습니다. 예를 들어 우리는 분포가 양의 영토 (skewness = 0.076)로 비뚤어지고 분포가 흉한 (kurtosis = 1.52) 것을 볼 수 있습니다. 금융 시계열이 맹금류로 잘 알려져 있기 때문에이 두 사실 중 누구도 시계열 분석을 수행 한 사람에게는 놀라움을 금치 못할 것입니다. 그러나 학습하는 자산 클래스와 기호에 따라 첨도 및 비대칭 정도가 많이 달라지는 점은 주목할 가치가 있습니다. 이 시리즈의 다음 부분에서 우리는 다른 Forex 및 비 Forex 기호가이 동일한 분석 (몇 가지 추가 통계 포함) 내에서 어떻게 비교되는지, 그리고이 통계가 역사적으로 수익성있는 거래 시스템을 생성하는 능력과 어떻게 관련되는지에 대해 살펴볼 것입니다 해당 데이터를 사용합니다. 특정 특성을 가진 배포판은 역사적으로 수익성 높은 전략을 쉽게 생성 할 수있는 반면, 다른 특성을 갖는 배포판은 에지를 찾기가 매우 어렵습니다.
통계에 정통한 사람들을 위해 기본 통계 분석 측면에서 유용하다고 생각하는 항목과 향후 게시물에서 설명 할 항목을 자유롭게 제공하십시오. 내 직업에 대해 더 자세히 알고 싶다면 어떻게 트레이딩 전략을 개발할 때 시계열 분석을 사용할 수 있습니까? 트레이딩 비디오, 트레이딩 시스템, 개발 및 자동 거래에 대한 건전하고 정직하고 투명한 접근법으로 가득 찬 웹 사이트 인 Asirikuy에 가입하는 것을 고려해보십시오. 일반적으로 나는이 기사를 즐겼기를 바랍니다! :영형)
알고리즘 트레이딩에서 R을 사용하는 3 가지 응답 : 간단한 시계열 특성 분석. 1 부 & # 8221;
[& # 8230;]이 일련의 게시물 중 일부는 Forex의 금융 시계열에서 간단한 기본 특성을 얻었습니다.
이 튜토리얼을 따르기 전에 기본 시계열 분석에 대한 이전 2 개의 (1, 2) R 튜토리얼을 읽으므로 기본 R 시리즈에 익숙해 지도록 조언합니다. [& # 8230; # 8230;]
죄송하지만이 문제에 직면 한 메신저 :
plot. window (& # 8230;)의 오류 : 유한 한 & # 8216; xlim & # 8217; 값.
또한 : 경고 메시지 :
1 : min (x)에서 min에 누락 된 인수가 없습니다. Inf를 반환합니다.
2 : max (x)에서 : max에 대한 누락 된 인수 없음; ~를 반환합니다.
3 : min (x) : min에 대한 누락 된 인수가 없습니다. Inf를 반환합니다.
4 : 최대 (x)에서 : max에 대한 누락 된 인수 없음; ~를 반환합니다.

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; 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.
The Rise of the Robots (Advisors…)
The Asset Management industry is on the verge of a major change. Over the last couple of years Robots Advisors (RA) have emerged as new players. The term itself is hard to define as it encompasses a large variety of services. Some are designed to help traditional advisers to better allocate their clients money and some are real “black box”. The user enter a few criteria (age , income, children etc…) and the robot proposes a tailor-made allocation. Between those two extremes a full range of offers is available. I found the Wikipedia definition pretty good. “They are a class of financial adviser that provides portfolio management online with minimal human intervention”. More precisely they use algorithm-based portfolio management to offer the full spectrum of services a traditional adviser would offer: dividend reinvesting, compliance reports, portfolio rebalancing, tax loss harvesting etc… (well this is what the quantitative investment community is doing for decades!). The industry is still in its infancy with most players still managing a small amount of money but I only realised how profound the change was when I was in NYC a few days ago. When RA get their names on TV adds or on the roof of NYC cab you know something big is happening…
it is getting more and more attention from the media and above all it makes a lot of sense from an investor perspective. There are actually two main advantages in using RA:
Significantly lower fees over traditional advisers Investment is made more transparent and simpler which is more appealing to people with limited financial knowledge.
In this post R is just an excuse to present nicely what is a major trend in the asset management industry. The chart below shows the market shares of most popular RA as of the end of 2014. The code used to generate the chart below can be found at the end of this post and the data is here.
Those figures are a bit dated given how fast this industry evolves but are still very informative. Not surprisingly the market is dominated by US providers like Wealthfront and Betterment but RA do emerge all over the world: Asia (8Now!), Switzerland (InvestGlass), France (Marie Quantier)….. It is starting to significantly affect the way traditional asset managers are doing business. A prominent example is the partnership between Fidelity and Betterment. Since December 2014 Betterment past the $2 billion AUM mark.
Despite all the above, I think the real change is ahead of us. Because they use less intermediaries and low commission products (like ETFs) they charge much lower fees than traditional advisers. RA will certainly gain significant market shares but they will also lowers fees charged by the industry as a whole. Ultimately it will affect the way traditional investment firms do business. Active portfolio management which is having a tough time for some years now will suffer even more. The high fees it charges will be even harder to justify unless it reinvents itself. Another potential impact is the rise of ETFs and low commission financial products in general. Obviously this has started a while ago but I do think the effect will be even more pronounced in the coming years. New generations of ETFs track more complex indices and custom made strategies. This trend will get stronger inevitably.
As usual any comments welcome.
R financial time series tips everyone should know about.
There are many R time series tutorials floating around on the web this post is not designed to be one of them. Instead I want to introduce a list of the most useful tricks I came across when dealing with financial time series in R. Some of the functions presented here are incredibly powerful but unfortunately buried in the documentation hence my desire to create a dedicated post. I only address daily or lower frequency times series. Dealing with higher frequency data requires specific tools: data. table or highfrequency packages are some of them.
xts : The xts package is the must have when it comes to times series in R. The example below loads the package and creates a daily time series of 400 days normaly distributed returns.
merge. xts (package xts): This is incredibly powerful when it comes to binding two or more times series together whether they have the same length or not. The join argument does the magic! it determines how the binding is done.
apply. yearly/apply. monthly (package xts): Apply a specified function to each distinct period in a given time series object. The example below calculates monthly and yearly returns of the second series in the tsInter object. Note that I use the sum of returns (no compounding)
endpoints (package xts): Extract index values of a given xts object corresponding to the last observations given a period specified by on. The example gives the last day of the month returns for each series in the tsInter object using endpoint to select the date.
na. locf (package zoo): Generic function for replacing each NA with the most recent non-NA prior to it. Extremely useful when dealing with a time series with a few “holes” and when this time series is subsequently used as input for an R functions that does not accept arguments with NAs. In the example I create a time series of random prices then artificially includes a few NAs in it and replace them with the most recent value.
charts. PerformanceSummary (package PerformanceAnalytics): For a set of returns, create a wealth index chart, bars for per-period performance, and underwater chart for drawdown. This is incredibly useful as it displays on a single window all the relevant information for a quick visual inspection of a trading strategy. The example below turns the prices series into an xts object then displays a window with the 3 charts described above.
The list above is by no means exhaustive but once you master the functions describe in this post it makes the manipulation of financial time series a lot easier, the code shorter and the readability of the code better.
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.

Forex.
119 пользователей находятся здесь.
МОДЕРАТОРЫ.
wrayjustin 달러를위한 무역 펜 FXMarketMaker 전문 상인 Hot_Biscuits_ 모델 및 병 spicy_pasta RichJG Financial Astrologer El_Huachinango MOD finance_student Prop Trader о команде модераторов & raquo;
Reddit에 오신 것을 환영합니다.
인터넷의 첫 페이지.
수천 개의 커뮤니티 중 하나에 가입하십시오.
отправлено & # 32; 4 개월 전 & # 32; âвтор & # 32; El_Huachinango MOD & # 32; - & # 32; 발표.
отправлено & # 32; 1 день назад автор Chickenxchicken Released On Probation.
отправлено & # 32; 1 день назад & # 32; автор & # 32; sett0.
отправлено & # 32; 1 день назад & # 32; автор & # 32; Tride5.
отправлено & # 32; 2 일 전 & # 32; 평가 & # 32; GotNoCredditFam Market Analyst.
помощь правила сайта центр поддержки вики реддикет 모드 가이드 라인 связаться с нами.
приложенияи инструменты Reddit for iPhone Reddit for Android 모바일 웹 사이트 кнопки.
회신을 보내십시오. & # 32; & # 32; Политика конфиденциальности. &부; 2017 reddit 그래픽입니다. Все права защищены.
REDDIT 및 ALIEN 로고는 reddit inc의 등록 상표입니다.
& pi; Rendered by PID 34260 on app-319 at 2017-12-21 05:42:55.104603+00:00 running a84abeb country code: UA.

No comments:

Post a Comment