spikes_finder <- function(x, min_profit = 0.03) {
# generate all spikes as NA
is_spike <- rep(NA, length(x))
# initial position must always sell to ensure next position is buy
last_pos <- "sell" # buy or sell
# setting all other position as NA
last_buy_pos <- NA
last_sell_pos <- NA
last_buy_idx <- NA
last_sell_idx <- NA
# looping all sequence
for (a in seq(length(x))) {
prev_idx <- recurse_check(a, x, "back")
next_idx <- recurse_check(a, x, "forward")
if (a == 1 | a == length(x)) {
next
}
if (x[prev_idx] < x[a] & x[next_idx] < x[a]) {
if (last_pos == "sell") {
if (is.na(last_sell_pos)) {
next
}
if (x[a] > last_sell_pos) {
is_spike[last_sell_idx] <- NA
is_spike[a] <- 1
last_sell_idx <- a
last_sell_pos <- x[a]
next
}
} else {
if ((x[a] - last_buy_pos)/last_buy_pos < min_profit) {
next
}
# this condition only executed when the last position is buy and note selling
is_spike[a] <- 1 # high spike (sell)
last_pos <- "sell"
last_sell_pos <- x[a]
last_sell_idx <- a
}
} else if (x[prev_idx] > x[a] & x[next_idx] > x[a]) {
if (last_pos == "buy") {
if (x[a] < last_buy_pos) {
is_spike[last_buy_idx] <- NA
is_spike[a] <- 0
last_buy_idx <- a
last_buy_pos <- x[a]
}
next
}
is_spike[a] <- 0 # low spike (buy)
last_pos <- "buy"
last_buy_pos <- x[a]
last_buy_idx <- a
} else {
next
}
}
is_spike <- highest_spike_finder(x, is_spike)
message("All data executed!\n")
return(is_spike)
}
highest_spike_finder <- function(x, spikes) {
last_buy <- 1
last_sell <- 1
for (i in seq(length(spikes))) {
if (is.na(spikes[i]) & last_buy == 1 & last_sell == 1) {
next
}
if (is.na(spikes[i])) {
if (last_sell < last_buy) {
next
}
if (x[i] > x[last_sell]) {
spikes[i] <- 1
spikes[last_sell] <- NA
last_sell <- i
} else {
next
}
} else if (spikes[i] == 0) {
last_buy <- i
} else if (spikes[i] == 1) {
last_sell <- i
}
}
return(spikes)
}
# this function is used to last position that has no equal price
recurse_check <- function(idx, data, type = c("back", "forward")) {
type <- match.arg(type, c("back", "forward"))
if (idx == 1 | idx == length(data)) {
return(idx)
}
if (type == "back") {
if (data[idx - 1] == data[idx]) {
recurse_check(idx - 1, data, type = type)
} else {
return(idx-1)
}
} else {
if (data[idx + 1] == data[idx]) {
recurse_check(idx + 1, data, type = type)
} else {
return(idx + 1)
}
}
}
profit_calculator <- function(spikes_data, target_profit = .01) {
prev_pos <- NA
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.