quantlab.dataset.base.bar_before_on#

quantlab.dataset.base.bar_before_on(bars, date, n, caller, where)[source]#

Return the bar n bars before date on the bars bars gives.

The arithmetic behind BaseDataset.bar_before and Factor.bar_before (quantlab.factor.base), which differ only in the bars they count on and in the text naming them. The bars before date are those stamped strictly earlier; n=1 is the last of them and n=0 returns date itself.

Parameters:
barscallable

Called with date as a pd.Timestamp and returning the sorted bar timestamps, at least every one before date, as a pd.DatetimeIndex. Called only when the bars are needed, so n=0 reads nothing.

datestr, datetime.date or pd.Timestamp

The date to count back from.

nint

How many bars to count back; non-negative.

callerstr

The class name the error messages start with ("<caller>.bar_before(): ...").

wherecallable

Returns the text naming where the bars come from, for the history error (stores_text of the stores read); called only when that error is raised.

Returns:
pd.Timestamp

The timestamp of that bar.

Raises:
ValueError

If n is negative.

InsufficientHistoryError

If fewer than n bars exist before date.

Examples

>>> bars = pd.DatetimeIndex(["2024-01-05", "2024-01-08", "2024-01-09"])
>>> bar_before_on(lambda _: bars, "2024-01-08", 1, "Demo", lambda: "the demo bars")
Timestamp('2024-01-05 00:00:00')
>>> bar_before_on(lambda _: bars, "2024-01-08", 3, "Demo", lambda: "the demo bars")
Traceback (most recent call last):
quantlab.dataset.base.InsufficientHistoryError: Demo.bar_before(): only 1 bar(s) exist before '2024-01-08' in the demo bars, but 3 were requested.