在 R 中的 quantmod 包中使用 SMA() 函数时出错

时间:2021-05-30 04:00:04

标签: r quantmod

新手程序员在这里!

我正在尝试针对 FAANG 股票创建股票价格预测模型。我安装了 quantmod 包来计算技术指标(50/200 天 SMA、RSI、MACD),并将它们作为变量添加到包含股票价格和开盘/收盘价的数据集中。

FB = read.csv("FB.csv")
AAPL = read.csv("AAPL.csv")
AMZN = read.csv("AMZN.csv")
NFLX = read.csv("NFLX.csv")
GOOG = read.csv("GOOG.csv")

# We will need to manipulate the date data since it's pulling in as character strings.
FB$Date = dmy(FB$Date)
AAPL$Date = dmy(AAPL$Date)
AMZN$Date = dmy(AMZN$Date)
NFLX$Date = dmy(NFLX$Date)
GOOG$Date = dmy(GOOG$Date)

# To follow R best practices, we will need to adjust the variable names to be lowercase and replace . with _
names(FB) = c("date", "low", "open", "volume", "high", "close", "adjusted_close")
names(AAPL) = c("date", "low", "open", "volume", "high", "close", "adjusted_close")
names(AMZN) = c("date", "low", "open", "volume", "high", "close", "adjusted_close")
names(NFLX) = c("date", "low", "open", "volume", "high", "close", "adjusted_close")
names(GOOG) = c("date", "low", "open", "volume", "high", "close", "adjusted_close")

# We'll need to add technical indicators to the data set to further our analysis: 50/200 Day SMA, RSI, MACD
aapl_sma50 = SMA(Cl(AAPL), n = 50) #50 day SMA for AAPL
aapl_sma200 = SMA(Cl(AAPL), n = 200) #200 day SMA for AAPL
aapl_rsi = RSI(Cl(AAPL), n = 14) #14 day RSI for AAPL

当我运行 SMA 函数时,我收到此错误消息:

> aapl_sma50 = SMA(Cl(AAPL), n = 50) #50 day SMA for AAPL
Error in runSum(x, n) : ncol(x) > 1. runSum only supports univariate 'x'
> aapl_sma200 = SMA(Cl(AAPL), n = 200) #200 day SMA for AAPL
Error in runSum(x, n) : ncol(x) > 1. runSum only supports univariate 'x'
> aapl_rsi = RSI(Cl(AAPL), n = 14) #14 day RSI for AAPL

关于如何调试这个有什么想法吗?

2 个答案:

答案 0 :(得分:0)

由于您已经在使用 quantmod,因此您可以使用 getSymbols 下载数据。以下工作没有任何错误。

library(quantmod)
getSymbols(c('AAPL', 'AMZN')) #Add more symbols if needed 

aapl_sma50 = SMA(Cl(AAPL), n = 50) 
aapl_sma200 = SMA(Cl(AAPL), n = 200)
aapl_rsi = RSI(Cl(AAPL), n = 14)

答案 1 :(得分:0)

它使用默认数据集没有任何错误

library(quantmod)
SMA(Cl(ttrc), n = 50)