I have the following problem:
- I have df which consists of one column and 60 rows as in df = rnorm(60, 0.06, 0.2)
- I want to reorder the 60 rows in order that cumprod(df+1)[60] - cumprod(df+1)[55] is as close to 1 as possible.
- Additionally I want max(cumprod(df+1)) to be lower than 1.305 and higher than 1.295.
My code looks like this
start.time <- Sys.time()
set.seed(42)
vs = rnorm(60, 0.06, 0.2)
max_attempts = 200000
swaps_made = 0
for (step in 1:max_attempts) {
# Copy the vector and swap two random values
vs_new = vs
swap_inds1 = sample(55:60, 2, replace = FALSE)
swap_inds2 = sample(length(vs), 2, replace = FALSE)
vs_new[swap_inds1] = vs_new[swap_inds2]
vs_new[swap_inds2] = vs_new[swap_inds1]
vs2 <- as_tibble(cumprod(1+vs_new))
vs3 <- as_tibble(cumprod(1+vs))
if (abs(vs2[60,1]-vs2[55,1]) < abs(vs3[60,1]-vs3[55,1])) {
vs = vs_new
}
flat = ((vs2[60,1]-vs2[55,1]) < 1.05) & ((vs2[60,1]-vs2[55,1]) > 0.95)
peak= (max(vs2) < 1.305) & (max(vs2) > 1.295)
swaps_made = swaps_made + 1
if (peak && flat) {
break
}
}
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken
This "hill-climbing" (I don't know if I can name it like this) method does not yield any results for me.
My next idea would be use the arrangements package and to create permutations for subsets of my data, merge the permutated subsets and check if conditions are met. I am afraid though, that this might be another uneccessary detour I might take and wante to ask if you might have any idea about how to tackle this problem?