600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > python 量化交易_Quantsrat让R语言像Python一样进行策略回测和量化交易

python 量化交易_Quantsrat让R语言像Python一样进行策略回测和量化交易

时间:2019-01-19 21:55:34

相关推荐

python 量化交易_Quantsrat让R语言像Python一样进行策略回测和量化交易

使用Quantsrat包

Quantsrat用来建立策略、添加指标、生成信号、生成买卖规则等进行回测。效果类似优矿、万矿、米筐那样的Python量化平台一样。因为不能CRAN在线安装,安装过程中还有一些坑。希望本文可以帮大家更顺利开始R的量化交易学习。

安装Quantsrat

试了一下,看来Quantsrat没有加入CRAN。每次遇到这种情况知道安装不会太顺利

> 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./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./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./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./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-/bin/windows/Rtools/下载推荐的版本。就是recommended的那个。绿色的那个。

这网速,我都快吓哭了。

忘了,应该从同济大学的镜像下载。在https://mirrors./CRAN/bin/windows/Rtools/下载相同的文件。

这速度还是很感人了吧。

启动安装包。标准的Windows安装包。使用推荐配置,加入到系统PATH变量,然后一路下一步就搞定了。

说实话,安装的速度比下载的速度还慢。看来又该换电脑啦。谁家有闲置不用的好笔记本赠送么?哈

安装blotter和quantstrat包

安装blotter包的时候依旧是老问题。我在北京访问github轻微困难。期待微软尽快解决吧。

> devtools::install_github("braverock/blotter")Error: Failed to install 'unknown package' from GitHub: schannel: failed to receive handshake, SSL/TLS connection failed>

多试几次终于成功了。

里面询问是否升级zoo包的时候,直接回车,跳过即可。

> 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 htmlIBM htmlPortfReturns htmladdAcctTxnhtmladdDiv htmladdPortfInstr htmladdTxn htmlamznhtmlblotter-packagehtmlcalcPortfWgt htmlcalcPosAvgCosthtmlcalcTxnAvgCosthtmlcalcTxnValue htmlchart.ME htmlchart.Posnhtmlchart.Reconcilehtmlchart.Spread htmldailyTxnPLhtmlextractTxns htmlgetAccounthtmlgetByPortfhtmlgetBySymbol htmlgetEndEq htmlgetPortfAcct htmlgetPortfolio htmlgetPos htmlgetPosAvgCost htmlgetPosQty htmlgetTxns htmlhist.mcsimhtmlhist.txnsim htmlinitAcct htmlinitPortf htmlinitPosPL htmlinitSummary htmlinitTxn htmlis.accounthtmlis.portfolio htmlmcsimhtmlpennyPerShare htmlperTradeStats htmlplot.mcsimhtmlplot.txnsim htmlput.account htmlput.portfolio htmlquantile.mcsimhtmlquantile.txnsimhtmlsummary.mcsim htmlsummary.txnsimhtmltradeQuantileshtmltradeStatshtmltxnsim htmltxnsim.portfs htmltxnsim.portnames htmltxnsim.txns htmlupdateAccthtmlupdateEndEq htmlupdatePortf htmlupdatePosPL 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包。同样回车直接跳过升级。

> 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 addedNB: 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.deflatedhtmlSharpeRatio.haircut htmladd.distribution htmladd.distribution.constraint htmladd.indicator htmladd.init htmladd.rule htmladd.signalhtmladdOrder htmladdPosLimit htmlapply.paramsethtmlapply.paramset.signal.analysishtmlapplyIndicatorSignals htmlapplyIndicatorshtmlapplyParameterhtmlapplyRuleshtmlapplySignals htmlapplyStrategy htmlapplyStrategy.rebalancinghtmlbeanplot.signals htmlchart.forward htmlchart.forward.training htmlclone.orderbookhtmlclone.portfoliohtmldegrees.of.freedom htmldelete.paramsethtmldistributional.boxplot htmldotprofitHurdlehtmlenable.rule htmlget.strategy htmlgetOrderBook htmlgetOrders htmlgetParameterTable htmlgetPosLimit htmlinitOrdershtmlinitStrategy htmlinitSymbolhtmlbo htmlis.strategy htmlload.strategy htmlluxoraudithtmlmatch.names htmlosMaxPos htmlosNoOp htmlparamConstrainthtmlportfolio.luxorhtmlpost.signal.returns htmlprint.dof htmlprint.haircutSRhtmlprint.profitHurdle htmlprofitHurdle htmlput.orderbook htmlput.strategy htmlquantstrat-package htmlrm.strat htmlruleOrderProc htmlrulePctEquity htmlruleRevokehtmlruleSignalhtml 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 htmlsave.strategy htmlsetParameterConstraint htmlsetParameterDistributionhtmlsigComparison htmlsigCrossover htmlsigFormulahtmlsigPeak htmlsigThreshold htmlsigTimestamp 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 htmlsignal.obj.slope htmlsignal.path.plot htmlsignal.plot htmlspx htmlstatshtmlstratBBands htmlstratFaberhtmlstrategy htmltradeGraphs htmltradeOrderStatshtmlupdateOrders htmlupdateStrategyhtmlfinding 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)

完工

测试一下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': methodfrom 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

表面看是成功了。

我们运行一下quantstrat包的demo里面的maCross策略,也就是双均线策略、金叉策略。

多说一句,maCross还是一个知名的动画片,就是那个日版的《超时空要塞》。回忆涌上心头啊。

策略代码在 /braverock/quantstrat/blob/master/demo/maCross.R

这里誊抄一下。具体含义我们以后一点点分析。

##########################################################################################################################################################################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

看一下结果,很不错。一本万利啊

感谢阅读,欢迎关注和留言

量化投资与期货外汇散仙,基金保险水平也拿的出手

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。