简体   繁体   中英

Error when using SMA() function in quantmod package in R

Newbie programmer here!

I'm trying to create a stock price prediction model on FAANG stocks. I've installed the quantmod package to calculate technical indicators (50/200 day SMA, RSI, MACD) and add them as variables to a data set that includes stock price and open/close prices.

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

When I run the SMA functions, I get this error message:

> 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

Any ideas on how to debug this?

Since you are already using quantmod you can use getSymbols to download the data. The below works without any error.

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)

It works without any error using the default dataset

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM