Hi,
I've spent sometime on this, but being an R newbie, and despite reading furiously, I am stuck. All guidance would be appreciated.
I have created simplified exchange prices, and based on various ifelse consitions, should print the start of a trade as '1' and the exit as '0', and also record the entry and exit.price. I have got this to work to some extent, but ideally I would like the exit.price and trade.off columns to only be recorded in the first instance of the conditions becoming true - i.e. only on rows 7 and 14, when this part becomes true ifelse (prices$High >= lag(prices$High), 0, NA)
# A tibble: 14 × 8
Low High up_day p_type entry.price exit.price trade.on trade.off
<dbl> <dbl> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 100 110 NA NA NA NA NA NA
2 110 130 NA NA NA 110 NA 0
3 100 120 Up P.High 100 NA 1 NA
4 90 110 NA NA NA NA NA NA
5 80 100 NA NA NA NA NA NA
6 70 90 NA NA NA NA NA NA
7 80 95 NA NA NA 90 NA 0
8 90 105 NA NA NA 95 NA 0
9 100 110 NA NA NA 105 NA 0
10 105 120 Up P.High 105 110 1 0
11 108 110 NA NA NA NA NA NA
12 108 109 NA NA NA NA NA NA
13 90 100 NA NA NA NA NA NA
14 95 110 NA NA NA 100 NA 0
So far my code looks like this:
note: using Dplyr
for (i in 1:nrow(prices)) {
print("Start")
prices$entry.price <- ifelse (prices$p_type == "P.High" & prices$up_day == "Up", prices$Low, NA)
prices$trade.on <- ifelse (prices$p_type == "P.High" & prices$up_day == "Up", 1, NA)
i <- 1
if (i <= 1) {
prices$exit.price <- ifelse (prices$High >= lag(prices$High), lag(prices$High), NA)
prices$trade.off <- ifelse (prices$High >= lag(prices$High), 0, NA)
i <- i - 1
} else {
NA
}
print("End")
}
I tried to use an if else argument to limit the nested ifelse conditions to only run after trade.on becomes 1, but that doesn't seem to work at all. I'm very much out of my depth!