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

感謝閱讀,歡迎關注和留言 量化投資與期貨外匯散仙,基金保險水平也拿的出手
相關文章
相關標籤/搜索