rquantmodcase-whentidyquant

Case_when dplyr


I am trying to create a buy/sell signal. I am trying to assign the signal using a case_when statement. I created several new columns using tidyquant TQ_MUTATE in a previous step. This only assigns the "possible up" and "possible down" signals.

What am I doing wrong?

df_with_decisions <- test %>% group_by(symbol) %>% mutate(

signal = case_when(
   (EMA_9 > EMA_55) ~ "possible up",
  (EMA_9 > EMA_55 && EVWMA_9 > EMA_55) ~ "watch upward",
  (EMA_9 > EMA_55 && EMA_21 >= EMA_55 && EVWMA_9 > EMA_55) ~ "buy",
  (EMA_9 > EMA_55 && EMA_21 >= EMA_55 && EVWMA_9 > EMA_55 && EVWMA_21 > EMA_55) ~ "strong_buy",
  EMA_9 < EMA_55 ~ "possible down",
  (EMA_9 < EMA_55 && EVWMA_9 < EMA_55) ~ "watch downward",
  (EMA_9 < EMA_55 && EMA_21 <= EMA_55 && EVWMA_9 < EMA_55) ~ "sell",
  (EMA_9 < EMA_55 && EMA_21 <= EMA_55 && EVWMA_9 < EMA_55 && EVWMA_21 < EMA_55) ~ "strong_sell",
  ),

previous_signal = lag(signal, 1),

decision = case_when(
  signal == previous_signal ~ "hold",
  TRUE ~ signal    )  )

Solution

  • Logical error too.

    case_when(
      (5 > 3) ~ "Hi",
      ((5 > 3) & (6 > 3)) ~ "Hello"
    )
    

    This will not print Hello