Skip to content

Instantly share code, notes, and snippets.

@davidzhaodz
Last active January 6, 2021 14:30
Show Gist options
  • Save davidzhaodz/8d6fefa61c01914163e964fa081395e3 to your computer and use it in GitHub Desktop.
Save davidzhaodz/8d6fefa61c01914163e964fa081395e3 to your computer and use it in GitHub Desktop.
def get_events(close, t_events, pt_sl, target, min_ret, num_threads,
vertical_barrier_times=False, side=None):
"""
:param close: (series) Close prices
:param t_events: (series) of t_events.
These are timestamps that will seed every triple barrier.
:param pt_sl: (2 element array) element 0, indicates the profit taking level;
element 1 is stop loss level.
A non-negative float that sets the width of the two barriers.
A 0 value means that the respective horizontal barrier will be disabled.
:param target: (series) of values that are used (in conjunction with pt_sl)
to determine the width of the barrier.
:param min_ret: (float) The minimum target return required for running a triple barrier search.
:param num_threads: (int) The number of threads concurrently used by the function.
:param vertical_barrier_times: (series) A pandas series with the timestamps of the vertical barriers.
:param side: (series) Side of the bet (long/short) as decided by the primary model
:return: (data frame) of events
-events.index is event's starttime
-events['t1'] is event's endtime
-events['trgt'] is event's target
-events['side'] (optional) implies the algo's position side
"""
# 1) Get target
target = target.loc[target.index.intersection(t_events)]
target = target[target > min_ret] # min_ret
# 2) Get vertical barrier (max holding period)
if vertical_barrier_times is False:
vertical_barrier_times = pd.Series(pd.NaT, index=t_events)
# 3) Form events object, apply stop loss on vertical barrier
if side is None:
side_ = pd.Series(1., index=target.index)
pt_sl_ = [pt_sl[0], pt_sl[0]]
else:
side_ = side.loc[target.index]
pt_sl_ = pt_sl[:2]
events = pd.concat({'t1': vertical_barrier_times, 'trgt': target, 'side': side_},
axis=1)
events = events.dropna(subset=['trgt'])
# Apply Triple Barrier
df0 = MultiProcessingFunctions.mp_pandas_obj(func=apply_pt_sl_on_t1,
pd_obj=('molecule', events.index),
num_threads=num_threads,
close=close,
events=events,
pt_sl=pt_sl_)
events['t1'] = df0.dropna(how='all').min(axis=1) # pd.min ignores nan
if side is None:
events = events.drop('side', axis=1)
return events
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment