Quantsrat让R语言像Python同样进行策略回测和量化交易

使用Quantsrat包

Quantsrat用来创建策略、添加指标、生成信号、生成买卖规则等进行回测。效果相似优矿、万矿、米筐那样的Python量化平台同样。由于不能CRAN在线安装,安装过程当中还有一些坑。但愿本文能够帮你们更顺利开始R的量化交易学习。html

安装Quantsrat

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

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

package ‘devtools’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\chang\AppData\Local\Temp\RtmpSmSzSd\downloaded_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 KB

package ‘FinancialInstrument’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\chang\AppData\Local\Temp\RtmpSmSzSd\downloaded_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 MB

package ‘PerformanceAnalytics’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\chang\AppData\Local\Temp\RtmpSmSzSd\downloaded_packages
> install.packages("zoo")

  There is a binary version available but the source version is later:
    binary source needs_compilation
zoo  1.8-6  1.8-7              TRUE

  Binaries will be installed
trying 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 MB

package ‘zoo’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\chang\AppData\Local\Temp\RtmpSmSzSd\downloaded_packages
>

再安装Rtools

http://cran.r-project.org/bin/windows/Rtools/下载推荐的版本。就是recommended的那个。绿色的那个。git

file

这网速,我都快吓哭了。github

file

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

file

这速度仍是很感人了吧。segmentfault

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

file

file

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

安装blotter和quantstrat包

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

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

多试几回终于成功了。ide

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

> devtools::install_github("braverock/blotter")
Downloading GitHub repo braverock/blotter@master
These 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:\Users\chang\AppData\Local\Temp\RtmpSmSzSd\remotesf9c12655770\braverock-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 - i386
C:/Rtools/mingw_32/bin/gcc  -I"E:/R-36~1.2/include" -DNDEBUG          -O3 -Wall  -std=gnu99 -mtune=generic -c calcPosAvgCost.c -o calcPosAvgCost.o
C:/Rtools/mingw_32/bin/gcc  -I"E:/R-36~1.2/include" -DNDEBUG          -O3 -Wall  -std=gnu99 -mtune=generic -c init.c -o init.o
C:/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 -lR
installing to E:/R-3.6.2/library/00LOCK-blotter/00new/blotter/libs/i386

*** arch - x64
C:/Rtools/mingw_64/bin/gcc  -I"E:/R-36~1.2/include" -DNDEBUG          -O2 -Wall  -std=gnu99 -mtune=generic -c calcPosAvgCost.c -o calcPosAvgCost.o
C:/Rtools/mingw_64/bin/gcc  -I"E:/R-36~1.2/include" -DNDEBUG          -O2 -Wall  -std=gnu99 -mtune=generic -c init.c -o init.o
C:/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 -lR
installing 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@master
These 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:\Users\chang\AppData\Local\Temp\RtmpSmSzSd\remotesf9c2cae58d7\braverock-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 - i386
C:/Rtools/mingw_32/bin/gcc  -I"E:/R-36~1.2/include" -DNDEBUG          -O3 -Wall  -std=gnu99 -mtune=generic -c firstCross.c -o firstCross.o
C:/Rtools/mingw_32/bin/gcc  -I"E:/R-36~1.2/include" -DNDEBUG          -O3 -Wall  -std=gnu99 -mtune=generic -c init.c -o init.o
C:/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 -lR
installing to E:/R-3.6.2/library/00LOCK-quantstrat/00new/quantstrat/libs/i386

*** arch - x64
C:/Rtools/mingw_64/bin/gcc  -I"E:/R-36~1.2/include" -DNDEBUG          -O2 -Wall  -std=gnu99 -mtune=generic -c firstCross.c -o firstCross.o
C:/Rtools/mingw_64/bin/gcc  -I"E:/R-36~1.2/include" -DNDEBUG          -O2 -Wall  -std=gnu99 -mtune=generic -c init.c -o init.o
C:/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 -lR
installing 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 topic
Rd 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 topic
Rd 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 topic
Rd 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.numeric

Registered S3 method overwritten by 'xts':
  method     from
  as.zoo.xts zoo 
载入须要的程辑包:TTR
Registered 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仍是一个知名的动画片,就是那个日版的《超时空要塞》。回忆涌上心头啊。

file

策略代码在 github的demo里的quantstrat/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 later
ttz<-Sys.getenv('TZ')
Sys.setenv(TZ='UTC')

suppressWarnings(rm("order_book.macross",pos=.strategy))
suppressWarnings(rm("account.macross","portfolio.macross",pos=.blotter))
suppressWarnings(rm("account.st","portfolio.st","stock.str","stratMACROSS",'start_t','end_t'))


stock.str='AAPL' # what are we trying it on
currency('USD')
stock(stock.str,currency='USD',multiplier=1)

startDate="1999-12-31"
initEq=1000000
portfolio.st='macross'
account.st='macross'
initPortf(portfolio.st,symbols=stock.str)
initAcct(account.st,portfolios=portfolio.st, initEq=initEq)
initOrders(portfolio=portfolio.st)

stratMACROSS<- strategy(portfolio.st)

stratMACROSS <- add.indicator(strategy = stratMACROSS, name = "SMA", arguments = list(x=quote(Cl(mktdata)), n=50),label= "ma50" )
stratMACROSS <- add.indicator(strategy = stratMACROSS, name = "SMA", arguments = list(x=quote(Cl(mktdata)[,1]), n=200),label= "ma200")

stratMACROSS <- add.signal(strategy = stratMACROSS,name="sigCrossover",arguments = list(columns=c("ma50","ma200"), relationship="gte"),label="ma50.gt.ma200")
stratMACROSS <- add.signal(strategy = stratMACROSS,name="sigCrossover",arguments = list(column=c("ma50","ma200"),relationship="lt"),label="ma50.lt.ma200")

stratMACROSS <- add.rule(strategy = stratMACROSS,name='ruleSignal', arguments = list(sigcol="ma50.gt.ma200",sigval=TRUE, orderqty=100, ordertype='market', orderside='long'),type='enter')
stratMACROSS <- add.rule(strategy = stratMACROSS,name='ruleSignal', arguments = list(sigcol="ma50.lt.ma200",sigval=TRUE, orderqty='all', ordertype='market', orderside='long'),type='exit')

# if you want a long/short Stops and Reverse MA cross strategy, you'd add two more rules for the short side:

# stratMACROSS <- add.rule(strategy = stratMACROSS,name='ruleSignal', arguments = list(sigcol="ma50.lt.ma200",sigval=TRUE, orderqty=-100, ordertype='market', orderside='short'),type='enter')
# stratMACROSS <- add.rule(strategy = stratMACROSS,name='ruleSignal', arguments = list(sigcol="ma50.gt.ma200",sigval=TRUE, orderqty=100, ordertype='market', orderside='short'),type='exit')

getSymbols(stock.str,from=startDate)
for(i in stock.str)
  assign(i, adjustOHLC(get(i),use.Adjusted=TRUE))

start_t<-Sys.time()
out<-applyStrategy(strategy=stratMACROSS , portfolios=portfolio.st)
end_t<-Sys.time()
print(end_t-start_t)

start_t<-Sys.time()
updatePortf(Portfolio='macross',Dates=paste('::',as.Date(Sys.time()),sep=''))
end_t<-Sys.time()
print("trade blotter portfolio update:")
print(end_t-start_t)

chart.Posn(Portfolio='macross',Symbol=stock.str)
add_SMA(n=50 , on=1,col='blue')
add_SMA(n=200, on=1)

book    = getOrderBook('macross')
stats   = tradeStats('macross')
ptstats = perTradeStats('macross')
rets    = PortfReturns('macross')
txns    = getTxns('macross', stock.str)

#Date workaround, remove later
Sys.setenv(TZ=ttz)

###############################################################################
# R (http://r-project.org/) Quantitative Strategy Model Framework
#
# Copyright (c) 2009-2012
# Peter Carl, Dirk Eddelbuettel, Brian G. Peterson,
# Jeffrey Ryan, Joshua Ulrich, and Garrett See
#
# This library is distributed under the terms of the GNU Public License (GPL)
# for full details see the file COPYING
#
# $Id$
#
###############################################################################

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

file

感谢阅读,欢迎关注和留言 量化投资与期货外汇散仙,基金保险水平也拿的出手
相关文章
相关标签/搜索