Gosatron
Gosatron

Reputation: 3

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    )  )

Upvotes: 0

Views: 610

Answers (3)

Try to use the brackets as much as you think it was helpful. I always finish with TRUE at the end of case_when. Mutate is such a milestone in tandem with Case_when. This is an example:

mutate(Intensidad_guerra = case_when(
     (MD_P2_filt$battle_type %in% c("pitched battle") | MD_P2_filt$battle_type %in% c("siege")) ~ "nivel alto",
                                  MD_P2_filt$battle_type %in% c("ambush")  ~"nivel medio",
                                  TRUE ~ "nivel bajo")) 

Upvotes: 0

Shan R
Shan R

Reputation: 541

Logical error too.

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

This will not print Hello

Upvotes: 0

akrun
akrun

Reputation: 887501

The issue would be that && which returns a single TRUE/FALSE output instead of logical vector of the same length as input

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    )  )

Upvotes: 1

Related Questions