Riddhanand Mohapatra
Riddhanand Mohapatra

Reputation: 25

How to use previous row value in a data frame for complicated 'if' conditions to determine current value in R

I am really stuck with a loop thingy in R.

I have a table as follows -

Date ROC
12/05/21 65
13/05/21 33
14/05/21 21
15/05/21 -5
16/05/21 7
17/05/2 2
18/05/2 18
19/05/21 25
20/05/21 33
21/05/21 41
22/05/21 25
23/05/21 7

So, I want to create a 3rd column called Trade Signal which produces one of the following results - 'buy' and 'not in position'

The condition is that if the current ROC > 0 and if last 5 ROC's are also > 0, then return 'BUY'. Else it should return 'NOT IN POSITION'.

If possible I would also like to add another way more complicated condition - if there is a running "BUY" in the 3rd column - return 'already in position' in the 3rd column and if already in position and when roc < 0, return 'close position'. It does not return "BUY" when a position is already open and once closed, it can return "BUY" again (as long as the other condition is met).

Upvotes: 0

Views: 50

Answers (1)

user17714926
user17714926

Reputation:

library(dplyr)

df <- df %>% 
  rowwise() %>%
  mutate(Trade_Signal=ifelse(ROC > 0 && 
                             (ROC %in% df$ROC[(length(df$ROC)-5): 
                                              length(df$ROC)])), 
                             'BUY', 'NOT IN POSITION'))

The second part of the condition should really be in a function. If it gets any more complicated, the entire ifelseshould come out into a function that returns bool. Trade_Signal=ROCCondition(ROC, df$ROC)

Upvotes: 2

Related Questions