Quantstratを使う4

Quantstratを使う3」から引き続きQuantstratの使い方を学習中。

というかハマっているw。
色々なものがパッケージ化されているため便利な反面、隠蔽されているということでもあり、スクラッチで実装する方法が直ぐに分かるものでも、実現方法が分からない!
そんなわけで1つずつ確認中。

今日は、ハマっている問題を解決する過程で確認したことのメモ。

前回は、特定のテクニカル(例えば移動平均線)の値より終値が高い場合に、ロングエントリーするロジックの実装方法を学んだ。

今回は、特定のテクニカル(ROCを使う)が指定した値以上の場合にロングエントリーするロジックの実装方法を学ぶ。

ポイントは3つ。
1つ目はadd.indicatorでインディケータにラベル(名前)を付けること(インディケータの定義)。
ここでは「roc」というラベル(名前)を付けた。インディケータに使用する関数をnameで指定(今回はROC関数を使用)し、ROCの計算期間はnROCで指定しており、今回は20とした。

add.indicator(strategy.st, name="ROC",
              arguments=list(x=quote(Cl(mktdata)), n=nROC),
              label="roc")

2つ目は、先ほど定義したインディケータを使用したシグナル発生条件の定義を行う(シグナルの定義)。
ここでは、「roc」と名付けたインディケータが、閾値(今回はrocThreshold=0.01とした)より大きい場合(「relationship=gt」)に買い付けるというシグナル発生条件を定義した。

add.signal(strategy.st, name="sigThreshold",
           arguments=list(column="roc", threshold=rocThreshold, 
                          relationship="gt", cross=FALSE),
           label="longEntry")

3つ目は、シグナルが発生した場合の売買ルールを定義する。
売買ルール名をlabelに定義(この例では「EnterLongByRoc」)し、新規建てか既存解消かの種類をtypeで指定(この例では「enter」なので新規)し、エントリー発動条件・売買種類・売買量などをargumentsにlistで指定する(この例では「longEntry」という名前のシグナルによって売買を発動し、longのオーダーをだし、売買量は100000)。

add.rule(strategy.st, 
         name="ruleSignal", 
         arguments=list(sigcol="longEntry", 
                        sigval=TRUE, 
                        orderside="long", 
                        ordertype="market", 
                        prefer="Open", 
                        orderqty=100000,
                        replace=FALSE
         ), 
         type="enter", 
         label = "EnterLongByRoc")

全てのソースは下記。

########################################### Initialize #########################################
# ワーキングディレクトリの指定
setwd("D:\\dev\\DataAnalysis\\RTrade\\quantStrat")

require(quantstrat)
require(PerformanceAnalytics)

# Settings
currency('JPY')
Sys.setenv(TZ="UTC")
symbols <- c(
  "YJ7203"
)

suppressMessages(getSymbols(symbols, from=from, to=to, src="yahooj", adjust=TRUE))  
stock(symbols, currency="JPY", multiplier=1)

initDate="2006-01-01"
from="2006-01-01"
to="2015-11-30"

# control the width of output to my R console.
options(width=70)

# trade sizing and initial equity settings
tradeSize <- 100000
initEq <- tradeSize*length(symbols)

strategy.st <- "RocLongOnlyStrategy"
portfolio.st <-"RocPort"
account.st <-"RocAccount"

# the removal of the strategy is necessary for rerunning the strategy
rm.strat(strategy.st)

# the portfolio must be initialized before the account and the orders
initPortf(portfolio.st, symbols=symbols, initDate=initDate, currency='JPY')
initAcct(account.st, portfolios=portfolio.st, initDate=initDate, currency='JPY',initEq=initEq)
initOrders(portfolio.st, initDate=initDate)

# initialize the strategy
strategy(strategy.st, store=TRUE)

########################################### tradeIndicator #########################################
# parameters
nROC<-20
rocThreshold<-0.01


# indicators
# 1) The add.indicator function call
# 2) The name of the strategy to add the indicator to (which I always call strategy.st, standing for strategy string)
# 3) The name of the indicator function, in quotes (E.G. such as “SMA”, “RSI”, etc.)
# 4) The arguments to the above indicator function, which are the INPUTS in this statement arguments=list(INPUTS)
# 5) The label that signals and possibly rules will use&#8211;which is the column name in the mktdata object.

add.indicator(strategy.st, name="ROC",
              arguments=list(x=quote(Cl(mktdata)), n=nROC),
              label="roc")

# a quick way of inspecting indicator output
resultApplyInd <- applyIndicators(strategy.st, mktdata=OHLC(YJ7203))

########################################### tradeSignals #########################################
# 1) The call to add.signal
# 2) The name of the strategy (again, strategy.st makes this very simple)
# 3) The name of the signal function (the majority of which are on display in the preceding block of code)
# 4) The arguments to said signal function, passed in the same way they are to indicators (that is, arguments=list(args)), but which are far more similar compared to indicators
# 5) The label for the signal column, which is highly similar to the labeling for indicator columns.

add.signal(strategy.st, name="sigThreshold",
           arguments=list(column="roc", threshold=rocThreshold, 
                          relationship="gt", cross=FALSE),
           label="longEntry")

########################################### tradeRules #########################################
#rules
add.rule(strategy.st, 
         name="ruleSignal", 
         arguments=list(sigcol="longEntry", 
                        sigval=TRUE, 
                        orderside="long", 
                        ordertype="market", 
                        prefer="Open", 
                        orderqty=100000,
                        replace=FALSE
         ), 
         type="enter", 
         label = "EnterLongByRoc")

########################################### execute strategy #########################################
# apply strategy
t1 <- Sys.time()
out <- applyStrategy(strategy=strategy.st,portfolios=portfolio.st)
applyStrategy(strategy.st,portfolio.st)
t2 <- Sys.time()
print(t2-t1)

# set up analytics
updatePortf(portfolio.st)
dateRange <- time(getPortfolio(portfolio.st)$summary)[-1]
updateAcct(portfolio.st,dateRange)
updateEndEq(account.st)

chart.Posn(portfolio.st)

実行結果はmktdataに記録され、Viewによって確認できる。

View(mktdata)

可視化は下記で。でも見づらいので、mktdataの内容をCSVExcelに書き込んで可視化したほうが良い。

chart.Posn(portfolio.st)