python 量化交易_Quantsrat让R语言像Python一样进行策略回测和量化交易
使用Quantsrat包
Quantsrat用來建立策略、添加指標(biāo)、生成信號(hào)、生成買賣規(guī)則等進(jìn)行回測(cè)。效果類似優(yōu)礦、萬礦、米筐那樣的Python量化平臺(tái)一樣。因?yàn)椴荒蹸RAN在線安裝,安裝過程中還有一些坑。希望本文可以幫大家更順利開始R的量化交易學(xué)習(xí)。
安裝Quantsrat
試了一下,看來Quantsrat沒有加入CRAN。每次遇到這種情況知道安裝不會(huì)太順利
> install.packages("quantsrat")Warning in install.packages : package ‘quantsrat’ is not available (for R version 3.6.2)先安裝devtools、FinancialInstrument、PerformanceAnalytics和zoo包
> install.packages("devtools")trying URL 'https://mirrors.tongji.edu.cn/CRAN/bin/windows/contrib/3.6/devtools_2.2.1.zip'Content type 'application/zip' length 342853 bytes (334 KB)downloaded 334 KBpackage ‘devtools’ successfully unpacked and MD5 sums checkedThe downloaded binary packages are in C:甥敳獲changAppDataLocalTempRtmpSmSzSddownloaded_packages> install.packages("FinancialInstrument")trying URL 'https://mirrors.tongji.edu.cn/CRAN/bin/windows/contrib/3.6/FinancialInstrument_1.3.1.zip'Content type 'application/zip' length 550826 bytes (537 KB)downloaded 537 KBpackage ‘FinancialInstrument’ successfully unpacked and MD5 sums checkedThe downloaded binary packages are in C:甥敳獲changAppDataLocalTempRtmpSmSzSddownloaded_packages> install.packages("PerformanceAnalytics") trying URL 'https://mirrors.tongji.edu.cn/CRAN/bin/windows/contrib/3.6/PerformanceAnalytics_1.5.3.zip'Content type 'application/zip' length 2866935 bytes (2.7 MB)downloaded 2.7 MBpackage ‘PerformanceAnalytics’ successfully unpacked and MD5 sums checkedThe downloaded binary packages are in C:甥敳獲changAppDataLocalTempRtmpSmSzSddownloaded_packages> install.packages("zoo") There is a binary version available but the source version is later: binary source needs_compilationzoo 1.8-6 1.8-7 TRUE Binaries will be installedtrying URL 'https://mirrors.tongji.edu.cn/CRAN/bin/windows/contrib/3.6/zoo_1.8-6.zip'Content type 'application/zip' length 1103089 bytes (1.1 MB)downloaded 1.1 MBpackage ‘zoo’ successfully unpacked and MD5 sums checkedThe downloaded binary packages are in C:甥敳獲changAppDataLocalTempRtmpSmSzSddownloaded_packages>再安裝Rtools
從http://cran.r-project.org/bin/windows/Rtools/下載推薦的版本。就是recommended的那個(gè)。綠色的那個(gè)。
這網(wǎng)速,我都快嚇哭了。
忘了,應(yīng)該從同濟(jì)大學(xué)的鏡像下載。在https://mirrors.tongji.edu.cn/CRAN/bin/windows/Rtools/下載相同的文件。
這速度還是很感人了吧。
啟動(dòng)安裝包。標(biāo)準(zhǔn)的Windows安裝包。使用推薦配置,加入到系統(tǒng)PATH變量,然后一路下一步就搞定了。
說實(shí)話,安裝的速度比下載的速度還慢。看來又該換電腦啦。誰家有閑置不用的好筆記本贈(zèng)送么?哈
安裝blotter和quantstrat包
安裝blotter包的時(shí)候依舊是老問題。我在北京訪問github輕微困難。期待微軟盡快解決吧。
> devtools::install_github("braverock/blotter")Error: Failed to install 'unknown package' from GitHub: schannel: failed to receive handshake, SSL/TLS connection failed>多試幾次終于成功了。
里面詢問是否升級(jí)zoo包的時(shí)候,直接回車,跳過即可。
> devtools::install_github("braverock/blotter")Downloading GitHub repo braverock/blotter@masterThese packages have more recent versions available.Which would you like to update?1: All 2: CRAN packages only 3: None 4: zoo (1.8-6 -> 1.8-7) [CRAN]Enter one or more numbers, or an empty line to skip updates:√ checking for file 'C:甥敳獲changAppDataLocalTempRtmpSmSzSdemotesf9c12655770braverock-blotter-3630fde/DESCRIPTION' ...- preparing 'blotter': (862ms)√ checking DESCRIPTION meta-information ... - cleaning src- checking for LF line-endings in source and make files and shell scripts (707ms)- checking for empty or unneeded directories- looking to see if a 'data/datalist' file should be added- building 'blotter_0.14.7.tar.gz' * installing *source* package 'blotter' ...** using staged installation** libs*** arch - i386C:/Rtools/mingw_32/bin/gcc -I"E:/R-36~1.2/include" -DNDEBUG -O3 -Wall -std=gnu99 -mtune=generic -c calcPosAvgCost.c -o calcPosAvgCost.oC:/Rtools/mingw_32/bin/gcc -I"E:/R-36~1.2/include" -DNDEBUG -O3 -Wall -std=gnu99 -mtune=generic -c init.c -o init.oC:/Rtools/mingw_32/bin/gcc -shared -s -static-libgcc -o blotter.dll tmp.def calcPosAvgCost.o init.o -LE:/R-36~1.2/bin/i386 -lRinstalling to E:/R-3.6.2/library/00LOCK-blotter/00new/blotter/libs/i386*** arch - x64C:/Rtools/mingw_64/bin/gcc -I"E:/R-36~1.2/include" -DNDEBUG -O2 -Wall -std=gnu99 -mtune=generic -c calcPosAvgCost.c -o calcPosAvgCost.oC:/Rtools/mingw_64/bin/gcc -I"E:/R-36~1.2/include" -DNDEBUG -O2 -Wall -std=gnu99 -mtune=generic -c init.c -o init.oC:/Rtools/mingw_64/bin/gcc -shared -s -static-libgcc -o blotter.dll tmp.def calcPosAvgCost.o init.o -LE:/R-36~1.2/bin/x64 -lRinstalling to E:/R-3.6.2/library/00LOCK-blotter/00new/blotter/libs/x64** R** data** demo** byte-compile and prepare package for lazy loading** help*** installing help indices converting help for package 'blotter' finding HTML links ... 好了 AcctReturns html IBM html PortfReturns html addAcctTxn html addDiv html addPortfInstr html addTxn html amzn html blotter-package html calcPortfWgt html calcPosAvgCost html calcTxnAvgCost html calcTxnValue html chart.ME html chart.Posn html chart.Reconcile html chart.Spread html dailyTxnPL html extractTxns html getAccount html getByPortf html getBySymbol html getEndEq html getPortfAcct html getPortfolio html getPos html getPosAvgCost html getPosQty html getTxns html hist.mcsim html hist.txnsim html initAcct html initPortf html initPosPL html initSummary html initTxn html is.account html is.portfolio html mcsim html pennyPerShare html perTradeStats html plot.mcsim html plot.txnsim html put.account html put.portfolio html quantile.mcsim html quantile.txnsim html summary.mcsim html summary.txnsim html tradeQuantiles html tradeStats html txnsim html txnsim.portfs html txnsim.portnames html txnsim.txns html updateAcct html updateEndEq html updatePortf html updatePosPL html ** building package indices** testing if installed package can be loaded from temporary location*** arch - i386*** arch - x64** testing if installed package can be loaded from final location*** arch - i386*** arch - x64** testing if installed package keeps a record of temporary installation path* DONE (blotter)>安裝quantstrat包。同樣回車直接跳過升級(jí)。
> devtools::install_github("braverock/quantstrat")Downloading GitHub repo braverock/quantstrat@masterThese packages have more recent versions available.Which would you like to update?1: All 2: CRAN packages only 3: None 4: zoo (1.8-6 -> 1.8-7) [CRAN]Enter one or more numbers, or an empty line to skip updates:√ checking for file 'C:甥敳獲changAppDataLocalTempRtmpSmSzSdemotesf9c2cae58d7braverock-quantstrat-9960e3e/DESCRIPTION' ...- preparing 'quantstrat': (1.4s)√ checking DESCRIPTION meta-information ... - cleaning src- checking for LF line-endings in source and make files and shell scripts (1.1s)- checking for empty or unneeded directories- looking to see if a 'data/datalist' file should be added NB: this package now depends on R (>= 3.5.0) WARNING: Added dependency on R >= 3.5.0 because serialized objects in serialize/load version 3 cannot be read in older versions of R. File(s) containing such objects: 'quantstrat/data/luxor.wfa.ples.RData' WARNING: Added dependency on R >= 3.5.0 because serialized objects in serialize/load version 3 cannot be read in older versions of R. File(s) containing such objects: 'quantstrat/luxor.wfa.ples.RData'- building 'quantstrat_0.16.6.tar.gz' * installing *source* package 'quantstrat' ...** using staged installation** libs*** arch - i386C:/Rtools/mingw_32/bin/gcc -I"E:/R-36~1.2/include" -DNDEBUG -O3 -Wall -std=gnu99 -mtune=generic -c firstCross.c -o firstCross.oC:/Rtools/mingw_32/bin/gcc -I"E:/R-36~1.2/include" -DNDEBUG -O3 -Wall -std=gnu99 -mtune=generic -c init.c -o init.oC:/Rtools/mingw_32/bin/gcc -shared -s -static-libgcc -o quantstrat.dll tmp.def firstCross.o init.o -LE:/R-36~1.2/bin/i386 -lRinstalling to E:/R-3.6.2/library/00LOCK-quantstrat/00new/quantstrat/libs/i386*** arch - x64C:/Rtools/mingw_64/bin/gcc -I"E:/R-36~1.2/include" -DNDEBUG -O2 -Wall -std=gnu99 -mtune=generic -c firstCross.c -o firstCross.oC:/Rtools/mingw_64/bin/gcc -I"E:/R-36~1.2/include" -DNDEBUG -O2 -Wall -std=gnu99 -mtune=generic -c init.c -o init.oC:/Rtools/mingw_64/bin/gcc -shared -s -static-libgcc -o quantstrat.dll tmp.def firstCross.o init.o -LE:/R-36~1.2/bin/x64 -lRinstalling to E:/R-3.6.2/library/00LOCK-quantstrat/00new/quantstrat/libs/x64** R** data** demo** inst** byte-compile and prepare package for lazy loading** help*** installing help indices converting help for package 'quantstrat' finding HTML links ... 好了 SharpeRatio.deflated html SharpeRatio.haircut html add.distribution html add.distribution.constraint html add.indicator html add.init html add.rule html add.signal html addOrder html addPosLimit html apply.paramset html apply.paramset.signal.analysis html applyIndicatorSignals html applyIndicators html applyParameter html applyRules html applySignals html applyStrategy html applyStrategy.rebalancing html beanplot.signals html chart.forward html chart.forward.training html clone.orderbook html clone.portfolio html degrees.of.freedom html delete.paramset html distributional.boxplot html dotprofitHurdle html enable.rule html get.strategy html getOrderBook html getOrders html getParameterTable html getPosLimit html initOrders html initStrategy html initSymbol html install.param.combo html is.strategy html load.strategy html luxoraudit html match.names html osMaxPos html osNoOp html paramConstraint html portfolio.luxor html post.signal.returns html print.dof html print.haircutSR html print.profitHurdle html profitHurdle html put.orderbook html put.strategy html quantstrat-package html rm.strat html ruleOrderProc html rulePctEquity html ruleRevoke html ruleSignal html Rd warning: C:/Users/chang/AppData/Local/Temp/Rtmpq66SHr/R.INSTALL28943475e45/quantstrat/man/ruleSignal.Rd:54: file link 'getPrice' in package 'quantmod' does not exist and so has been treated as a topicRd warning: C:/Users/chang/AppData/Local/Temp/Rtmpq66SHr/R.INSTALL28943475e45/quantstrat/man/ruleSignal.Rd:93: file link 'getPrice' in package 'quantmod' does not exist and so has been treated as a topicRd warning: C:/Users/chang/AppData/Local/Temp/Rtmpq66SHr/R.INSTALL28943475e45/quantstrat/man/ruleSignal.Rd:96: file link 'getPrice' in package 'quantmod' does not exist and so has been treated as a topic sample_random_multests html save.strategy html setParameterConstraint html setParameterDistribution html sigComparison html sigCrossover html sigFormula html sigPeak html sigThreshold html sigTimestamp html Rd warning: C:/Users/chang/AppData/Local/Temp/Rtmpq66SHr/R.INSTALL28943475e45/quantstrat/man/sigTimestamp.Rd:16: file link 'split.xts' in package 'xts' does not exist and so has been treated as a topicRd warning: C:/Users/chang/AppData/Local/Temp/Rtmpq66SHr/R.INSTALL28943475e45/quantstrat/man/sigTimestamp.Rd:18: file link '.indexday' in package 'xts' does not exist and so has been treated as a topic signal.generate.statistics html signal.obj.slope html signal.path.plot html signal.plot html spx html stats html stratBBands html stratFaber html strategy html tradeGraphs html tradeOrderStats html updateOrders html updateStrategy html finding level-2 HTML links ... done walk.forward html *** copying figures** building package indices** installing vignettes** testing if installed package can be loaded from temporary location*** arch - i386*** arch - x64** testing if installed package can be loaded from final location*** arch - i386*** arch - x64** testing if installed package keeps a record of temporary installation path* DONE (quantstrat)完工
測(cè)試一下quantstrat包是否安裝成功
> library(quantstrat)載入需要的程輯包:quantmod載入需要的程輯包:xts載入需要的程輯包:zoo載入程輯包:‘zoo’The following objects are masked from ‘package:base’: as.Date, as.Date.numericRegistered S3 method overwritten by 'xts': method from as.zoo.xts zoo 載入需要的程輯包:TTRRegistered S3 method overwritten by 'quantmod': method from as.zoo.data.frame zoo Version 0.4-0 included new data defaults. See ?getSymbols.載入需要的程輯包:blotter載入需要的程輯包:FinancialInstrument載入需要的程輯包:PerformanceAnalytics載入程輯包:‘PerformanceAnalytics’The following object is masked from ‘package:graphics’: legend載入需要的程輯包:foreach表面看是成功了。
我們運(yùn)行一下quantstrat包的demo里面的maCross策略,也就是雙均線策略、金叉策略。
多說一句,maCross還是一個(gè)知名的動(dòng)畫片,就是那個(gè)日版的《超時(shí)空要塞》。回憶涌上心頭啊。
策略代碼在 https://github.com/braverock/quantstrat/blob/master/demo/maCross.R
這里謄抄一下。具體含義我們以后一點(diǎn)點(diǎn)分析。
##########################################################################################################################################################################A simple moving average strategy to evaluate trade efficiency#checks on SMA of 50 days and SMA of 200 days#Author: R. Raghuraman("raghu"), Brian Peterson#########################################################################################################################################################################require(quantstrat)################ workaround to xts Date handling, remove laterttz看一下結(jié)果,很不錯(cuò)。一本萬利啊
感謝閱讀,歡迎關(guān)注和留言
量化投資與期貨外匯散仙,基金保險(xiǎn)水平也拿的出手
總結(jié)
以上是生活随笔為你收集整理的python 量化交易_Quantsrat让R语言像Python一样进行策略回测和量化交易的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python怎么编写视觉识别_Pytho
- 下一篇: python爬虫保存图片到指定文件夹_李