11"""Run bar sampler implementations.
22
3- AFML-compliant run bars per López de Prado Chapter 2.3 .
3+ Run bars based on López de Prado's cumulative run definition .
44
5- Run bar threshold formula:
5+ Tick-run threshold formula:
66 E[θ_T] = E[T] × max{P[b=1], 1-P[b=1]}
77
88Where:
99 E[T] = EWMA of bar lengths (ticks per bar)
1010 P[b=1] = buy probability
1111
12+ Volume and dollar variants use cumulative volume/value as the adaptive size
13+ in the same threshold calculation, rather than mixing value units with tick counts.
14+
1215CRITICAL: θ_T = max{Σ(all buys in bar), Σ(all sells in bar)}
1316 - NOT consecutive same-sided trades
1417 - NO reset on direction change within bar
@@ -51,8 +54,10 @@ def _calculate_run_bars_nb(
5154 npt .NDArray [np .float64 ],
5255 npt .NDArray [np .float64 ],
5356 npt .NDArray [np .float64 ],
57+ float ,
58+ float ,
5459]:
55- """Calculate AFML-compliant run bar indices.
60+ """Calculate cumulative weighted run bar indices.
5661
5762 AFML Chapter 2.3 formula:
5863 θ_T = max{Σ(all buys in bar), Σ(all sells in bar)}
@@ -68,7 +73,7 @@ def _calculate_run_bars_nb(
6873 sides : ndarray
6974 Array of trade signs (+1 for buy, -1 for sell)
7075 initial_expected_t : float
71- Initial expected ticks per bar (E[T])
76+ Initial expected total value per bar, in the same units as values
7277 initial_p_buy : float
7378 Initial buy probability P[b=1]
7479 alpha : float
@@ -78,9 +83,9 @@ def _calculate_run_bars_nb(
7883
7984 Returns
8085 -------
81- tuple of arrays
86+ tuple
8287 (bar_indices, thetas, expected_thetas, expected_ts, p_buys,
83- cumulative_buys, cumulative_sells)
88+ cumulative_buys, cumulative_sells, current_expected_t, current_p_buy )
8489 """
8590 n = len (values )
8691
@@ -137,10 +142,13 @@ def _calculate_run_bars_nb(
137142
138143 n_bars += 1
139144
140- # Update EWMAs after warmup period
145+ # Update EWMAs after warmup period.
146+ # expected_t is denominated in the same units as `values`: ticks when
147+ # every value is 1, and volume or dollars when those series are passed.
148+ # Updating it with the tick count collapses a value-scaled threshold.
141149 if n_bars > min_bars_warmup :
142- # Update E[T] - expected ticks per bar
143- expected_t = alpha * bar_tick_count + (1 - alpha ) * expected_t
150+ bar_value = cumulative_buys + cumulative_sells
151+ expected_t = alpha * bar_value + (1 - alpha ) * expected_t
144152
145153 # Update P[b=1] - buy probability
146154 bar_p_buy = bar_buy_count / bar_tick_count if bar_tick_count > 0 else 0.5
@@ -160,6 +168,8 @@ def _calculate_run_bars_nb(
160168 np .array (p_buys , dtype = np .float64 ),
161169 np .array (cumulative_buys_out , dtype = np .float64 ),
162170 np .array (cumulative_sells_out , dtype = np .float64 ),
171+ float (expected_t ),
172+ float (p_buy ),
163173 )
164174
165175
@@ -258,6 +268,8 @@ def sample(
258268 p_buys ,
259269 cumulative_buys ,
260270 cumulative_sells ,
271+ current_expected_t ,
272+ current_p_buy ,
261273 ) = _calculate_run_bars_nb (
262274 values ,
263275 sides ,
@@ -315,11 +327,7 @@ def sample(
315327 cum_sells = float (np .sum (bar_sides < 0 ))
316328 current_theta = max (cum_buys , cum_sells )
317329
318- last_expected_t = (
319- expected_ts [- 1 ] if len (expected_ts ) > 0 else float (self .expected_ticks_per_bar )
320- )
321- last_p_buy = p_buys [- 1 ] if len (p_buys ) > 0 else self .initial_p_buy
322- expected_theta = last_expected_t * max (last_p_buy , 1 - last_p_buy )
330+ expected_theta = current_expected_t * max (current_p_buy , 1 - current_p_buy )
323331
324332 bar = self ._create_ohlcv_bar (
325333 bar_ticks ,
@@ -330,8 +338,8 @@ def sample(
330338 "expected_run" : float (expected_theta ),
331339 "theta" : float (current_theta ),
332340 "expected_theta" : float (expected_theta ),
333- "expected_t" : float ( last_expected_t ) ,
334- "p_buy" : float ( last_p_buy ) ,
341+ "expected_t" : current_expected_t ,
342+ "p_buy" : current_p_buy ,
335343 "cumulative_buys" : float (cum_buys ),
336344 "cumulative_sells" : float (cum_sells ),
337345 },
@@ -369,7 +377,7 @@ def _empty_run_bars_df(self) -> pl.DataFrame:
369377
370378
371379class VolumeRunBarSampler (BarSampler ):
372- """Sample bars based on cumulative volume runs (AFML-compliant) .
380+ """Sample bars based on cumulative volume runs.
373381
374382 AFML Chapter 2.3 formula with volume weighting:
375383 θ_T = max{Σ(buy volumes in bar), Σ(sell volumes in bar)}
@@ -448,6 +456,8 @@ def sample(
448456 p_buys ,
449457 cumulative_buys ,
450458 cumulative_sells ,
459+ current_expected_t ,
460+ current_p_buy ,
451461 ) = _calculate_run_bars_nb (
452462 volumes , # Use volumes as values
453463 sides ,
@@ -503,11 +513,7 @@ def sample(
503513 # Calculate current theta (cumulative volumes)
504514 current_theta = max (buy_vol , sell_vol )
505515
506- last_expected_t = (
507- expected_ts [- 1 ] if len (expected_ts ) > 0 else initial_expected_t_scaled
508- )
509- last_p_buy = p_buys [- 1 ] if len (p_buys ) > 0 else self .initial_p_buy
510- expected_theta = last_expected_t * max (last_p_buy , 1 - last_p_buy )
516+ expected_theta = current_expected_t * max (current_p_buy , 1 - current_p_buy )
511517
512518 bar = self ._create_ohlcv_bar (
513519 bar_ticks ,
@@ -518,8 +524,8 @@ def sample(
518524 "expected_run" : float (expected_theta ),
519525 "theta" : float (current_theta ),
520526 "expected_theta" : float (expected_theta ),
521- "expected_t" : float ( last_expected_t ) ,
522- "p_buy" : float ( last_p_buy ) ,
527+ "expected_t" : current_expected_t ,
528+ "p_buy" : current_p_buy ,
523529 "cumulative_buys" : float (buy_vol ),
524530 "cumulative_sells" : float (sell_vol ),
525531 },
@@ -557,7 +563,7 @@ def _empty_run_bars_df(self) -> pl.DataFrame:
557563
558564
559565class DollarRunBarSampler (BarSampler ):
560- """Sample bars based on cumulative dollar value runs (AFML-compliant) .
566+ """Sample bars based on cumulative dollar value runs.
561567
562568 AFML Chapter 2.3 formula with dollar weighting:
563569 θ_T = max{Σ(buy dollars in bar), Σ(sell dollars in bar)}
@@ -635,6 +641,8 @@ def sample(
635641 p_buys ,
636642 cumulative_buys ,
637643 cumulative_sells ,
644+ current_expected_t ,
645+ current_p_buy ,
638646 ) = _calculate_run_bars_nb (
639647 dollar_volumes , # Use dollar volumes as values
640648 sides ,
@@ -702,11 +710,7 @@ def sample(
702710 sell_dollars = float (np .sum (bar_dollars [bar_sides < 0 ]))
703711 current_theta = max (buy_dollars , sell_dollars )
704712
705- last_expected_t = (
706- expected_ts [- 1 ] if len (expected_ts ) > 0 else initial_expected_t_scaled
707- )
708- last_p_buy = p_buys [- 1 ] if len (p_buys ) > 0 else self .initial_p_buy
709- expected_theta = last_expected_t * max (last_p_buy , 1 - last_p_buy )
713+ expected_theta = current_expected_t * max (current_p_buy , 1 - current_p_buy )
710714
711715 bar = self ._create_ohlcv_bar (
712716 bar_ticks ,
@@ -719,8 +723,8 @@ def sample(
719723 "expected_run" : float (expected_theta ),
720724 "theta" : float (current_theta ),
721725 "expected_theta" : float (expected_theta ),
722- "expected_t" : float ( last_expected_t ) ,
723- "p_buy" : float ( last_p_buy ) ,
726+ "expected_t" : current_expected_t ,
727+ "p_buy" : current_p_buy ,
724728 "cumulative_buys" : float (buy_dollars ),
725729 "cumulative_sells" : float (sell_dollars ),
726730 },
0 commit comments