自己撰寫指標 - I
到目前為止,你一直透過 add.indicator() 使用他人完全寫好的指標。現在該輪到你自己撰寫並套用自訂指標了。
你的指標函式將計算兩個不同指標的平均值,以建立一個 3.5 期的 RSI。做法如下:
- 接收一組價格序列。
- 計算 RSI 3。
- 計算 RSI 4。
- 回傳 RSI 3 與 RSI 4 的平均值。
這個 RSI 可以視為 RSI 3.5,因為它比 RSI 3 更長、比 RSI 4 更短。透過取平均,這個指標同時考量到 4 天前的影響,速度仍比單純的 RSI 4 更快,且能減少 RSI 3 與 RSI 4 的雜訊。
在本練習中,你會建立名為 calc_RSI_avg() 的指標函式,並將它加入你的策略 strategy.st。所有相關套件都已為你載入。
本練習屬於課程
R 的金融交易
練習說明
- 建立並命名函式
calc_RSI_avg,依序包含三個引數price、n1、n2。 - 計算回看期為
n1的 RSI,命名為RSI_1。 - 計算回看期為
n2的 RSI,命名為RSI_2。 - 計算
RSI_1與RSI_2的平均值,命名為RSI_avg。 - 使用 colnames() 將
RSI_avg的欄名設為RSI_avg,並回傳RSI_avg。 - 將此指標加入你的策略,輸入
n1 = 3與n2 = 4,並將此指標標記為RSI_3_4。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Write the calc_RSI_avg function
calc_RSI_avg <- function(price, n1, n2) {
# RSI 1 takes an input of the price and n1
RSI_1 <- RSI(price = price, n = ___)
# RSI 2 takes an input of the price and n2
RSI_2 <- RSI(price = price, n = ___)
# RSI_avg is the average of RSI_1 and RSI_2
RSI_avg <- (___ + ___)/2
# Your output of RSI_avg needs a column name of RSI_avg
colnames(RSI_avg) <- "___"
return(___)
}
# Add this function as RSI_3_4 to your strategy with n1 = 3 and n2 = 4
add.indicator(strategy.st, name = ___, arguments = list(price = quote(Cl(mktdata)), n1 = ___, n2 = ___), label = ___)