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.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的那个。绿色的那个。

3c7510af031ad9a7614667db04107ff3.png

这网速,我都快吓哭了。

34786aaef7af375abc09e3fba0c2ad9b.png

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

42da61d1898163ba12c4eeafeefd3bfb.png

这速度还是很感人了吧。

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

be0e44f20777eb818327da94668c3859.png
b6b5a83d7d801671e3d3460addf49938.png

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

安装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                             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包。同样回车直接跳过升级。

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

完工

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

表面看是成功了。

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

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

14d940c9f959778226e772777dde957f.png

策略代码在 https://github.com/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

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

18ad7b07a7d45b2eacb830aa996c9ae6.png

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值