-
Grouping bars by range and not by time
Hi,
Starting from a tick dataset,
I’m trying to create a function that performs resampling based on the range, specifically each time the maximum – minimum distance of the candle exceeds a certain value, the bar closes and another one begins. I’ve tried various solutions, and I had even opened a post, but the solution that was suggested to me didn’t actually achieve the result I want.Specifically, the function creates a new column “candela_range” where it assigns an increasing number, which increments by 1 every time the candle range changes. At that point, I can perform a groupby by “range_candela”. The problem is that the function was implemented inefficiently in Q language, and it’s very slow. How can I improve this function to leverage the Q language paradigm efficiently?
I’m sharing the starting dataset and an example of the result.
The Range bars chart consists of bars that have high/low range equal or less than the Range preference value. To calculate the first bar, we have to go backward in time to last starting point and build bars until the current time. Starting point can be: session open, start of trading week or start of trading month.
simpleRangeGroups:{[price_list;candela_list;range_target] / Number of elements n:count price_list; if[n=0; :()]; if[n=1; :enlist 1i]; / Initialize result result:n#0i; result[0]:1i; / Initialize state variables curr_idx:1i; curr_high:price_list[0]; curr_low:price_list[0]; curr_range:0f; / Efficient loop i:1; while[i0;candela_list[i-1];0i]; / Calculate if a new candle is needed new_candle:0b; / Condition 1: reference change if[curr_ref>prev_ref; new_candle:1b]; / Condition 2: range exceeds limits if[(not new_candle) and (curr_range>range_target) and ((curr_highcurr_price)); new_candle:1b ]; / Update state $[new_candle; [ / New candle curr_idx+:1i; curr_high:curr_price; curr_low:curr_price; curr_range:0f; ]; [ / Update high if necessary if[curr_price>curr_high; curr_range+:curr_price-curr_high; curr_high:curr_price; ]; / Update low if necessary if[curr_price
df_range: update candela_range: simpleRangeGroups[price;candela;0.0015999999] from df_start;
meta df_start
¡ c t f a
`idx “j” ` `</p><p>`candela “j” ` `
`date “d” ` `</p><p>`time “n” ` `
`ts_event “p” ` `</p><p>`price “f” ` `
`size “j” ` `</p><p>`side “c” ` `
`bid “j” ` `</p><p>`ask “j” ` `
`sym “s” ` `p
Sorry, there were no replies found.
Log in to reply.