Search code examples
rquantmod

Generalize "$-notation"


I'm still getting used to working in R and thought constructing a "simple" MACD-screener would be a great way to get into some of the inner workings of R. However, I have encountered the following problem. I've perfectly been able to calculate te MACD and signal line for a seperate stock. So now, in order to be able to scan multiple stocks, I have to generalize the code. My question in: "How can I use a variable (f.e. name of the stock currently being looked at) in the "$-notation"? After this I'm planning to do a "for loop" iterating over the names of stocks in a list-object. Is this a practical way of doing it?

Below I've inserted the code I have till now. In this code I'm looking to replace the "QQQ" with a variable.

library(quantmod)
tickers <- c('QQQ','SPY','APPL','MMM')

ema.s = 12
ema.l = 26
ema.k = 9
ema.t = 200

getSymbols(tickers, from = '2021-01-6',
           to = "2021-10-21",warnings = FALSE,
           auto.assign = TRUE)

QQQ$QQQ.EMA.S <- EMA(QQQ[,6], n = ema.s)
QQQ$QQQ.EMA.L <- EMA(QQQ[,6], n = ema.l)
QQQ$QQQ.MACD <- QQQ$QQQ.EMA.S - QQQ$QQQ.EMA.L
QQQ$QQQ.SIG <- EMA(QQQ$QQQ.MACD, n = ema.k)

Solution

  • You can use tidyquant to all of this in one go.

    library(tidyquant)
    
    ema.s = 12
    ema.l = 26
    
    tickers <- c('QQQ','SPY','AAPL','MMM')
    
    # get all the data in a tibble
    stock_data <- tq_get(tickers, 
                         from = '2021-01-6',
                         to = "2021-10-21")
    
    
    stock_data <- stock_data %>% 
      group_by(symbol) %>% 
      tq_mutate(select = adjusted,
                mutate_fun = MACD,
                n_fast = ema.s,
                n_slow = ema.l)
    
    stock_data 
    
    # A tibble: 800 x 10
    # Groups:   symbol [4]
       symbol date        open  high   low close   volume adjusted  macd signal
       <chr>  <date>     <dbl> <dbl> <dbl> <dbl>    <dbl>    <dbl> <dbl>  <dbl>
     1 QQQ    2021-01-06  307   312.  306.  308. 52809600     306.    NA     NA
     2 QQQ    2021-01-07  310.  316.  310.  315. 30394800     314.    NA     NA
     3 QQQ    2021-01-08  317.  319.  315.  319. 33955800     318.    NA     NA
     4 QQQ    2021-01-11  316.  317.  314.  314. 32746400     313.    NA     NA
     5 QQQ    2021-01-12  314.  316.  311.  314. 29266800     313.    NA     NA
     6 QQQ    2021-01-13  314.  317.  314.  316. 22898400     315.    NA     NA
     7 QQQ    2021-01-14  316.  318.  314.  314. 23500100     313.    NA     NA
     8 QQQ    2021-01-15  314.  315.  311.  312. 35118700     311.    NA     NA
     9 QQQ    2021-01-19  314.  317.  313.  316. 24537000     315.    NA     NA
    10 QQQ    2021-01-20  320.  325.  317.  324. 30728100     323.    NA     NA  
    

    If you want to do this in base R functions combined with only quantmod functions, check the quantmod tag, there are a few posts that use lapply to do this. If you don't find what you need, let me know.