开始使用免费开始使用

编写您自己的指标 - 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,包含三个参数 pricen1n2
  • 计算回看期为 n1 的 RSI,命名为 RSI_1
  • 计算回看期为 n2 的 RSI,命名为 RSI_2
  • 计算 RSI_1RSI_2 的平均值,命名为 RSI_avg
  • 使用 colnames()RSI_avg 的列名设置为 RSI_avg,并返回 RSI_avg
  • 将该指标加入到您的策略中,输入参数为 n1 = 3n2 = 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 = ___)
编辑并运行代码