R: trying to calculate RSI for a list of stocks

214 Views Asked by At

I am trying to add a data column with RSI values (from TTR package) to a data frame which contains stocks with historical price data. I am struggling when merging the data. So far i have this:

library(BatchGetSymbols) 
library(TTR)

first.date <- Sys.Date()-101
last.date <- Sys.Date()
l.out <- BatchGetSymbols(tickers = tickers_list,first.date = first.date,last.date = last.date, do.cache=FALSE)
my_data <- l.out$df.tickers
RSI <- by(my_data , my_data $ticker, function(sub) TTR::RSI(sub$price.close))

so far so good and i am able to generate the RSI values. First 14 values for RSI are NA (for each ticker), the rest are actual values. Where im struggling is when im trying to add this generated RSI data into "RSI" column in "my_data" data frame..

What im basically trying to do is combine the two data sets by:

my_data$RSI <- RSI

im getting the following error:

Error in set(x, j = name, value = value) : 
  Supplied 1617 items to be assigned to 113174 items of column 'RSI'. If you wish to 'recycle' the RHS please use rep() to make this intent clear to readers of your code.

I have also tried do.call:

my_data$rsi <- do.call(rbind, RSI)

but i get the following error as well:

Error in set(x, j = name, value = value) : 
  Supplied 113190 items to be assigned to 113174 items of column 'rsi'. If you wish to 'recycle' the RHS please use rep() to make this intent clear to readers of your code.
In addition: Warning messages:
1: In (function (..., deparse.level = 1)  :
  number of columns of result is not a multiple of vector length (arg 1340)
2: In set(x, j = name, value = value) :
  70 column matrix RHS of := will be treated as one vector

there seems to be a "16 values" mismatch.. any help would be appreciated. Thank you in advance.

1

There are 1 best solutions below

1
On

Is this output what you're looking for? This adds a column with the RSI() output to the Yahoo Finance data.

library(tidyverse)
library(TTR)
library(yfR)

tickers <- c("TSLA", "MMM")
first.date <- Sys.Date()-101
last.date <- Sys.Date()
l.out <- yf_get(tickers = tickers, first_date = first.date, last_date = last.date, do_cache=FALSE)
#> 
#> ── Running yfR for 2 stocks | 2022-07-30 --> 2022-11-08 (101 days) ──
#> 
#> ℹ Downloading data for benchmark ticker ^GSPC
#> ℹ (1/2) Fetching data for MMM
#> ✔    - got 70 valid rows (2022-08-01 --> 2022-11-07)
#> ✔    - got 100% of valid prices -- Well done !
#> ℹ (2/2) Fetching data for TSLA
#> ✔    - got 70 valid rows (2022-08-01 --> 2022-11-07)
#> ✔    - got 100% of valid prices -- Got it!
#> ℹ Binding price data
#> 
#> ── Diagnostics ─────────────────────────────────────────────────────────────────
#> ✔ Returned dataframe with 140 rows -- You got it !
#> ℹ Out of 2 requested tickers, you got 2 (100%)

my_data <- l.out %>%
  mutate(RSI = RSI(price_close))

Created on 2022-11-08 with reprex v2.0.2