编写您自己的指标 - 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 = ___)