Last active
January 6, 2021 13:57
-
-
Save davidzhaodz/15180b1039bd34c0855bb8aa5ab05bee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def apply_pt_sl_on_t1(close, events, pt_sl, molecule): | |
""" | |
:param close: (series) close prices | |
:param events: (series) of indices that signify "events" | |
:param pt_sl: (array) element 0, indicates the profit taking level; | |
element 1 is stop loss level | |
:param molecule: (an array) a set of datetime index values for processing | |
:return: (dataframe) timestamps at which each barrier was touched | |
""" | |
# apply stop loss/profit taking, if it takes place before t1 (end of event) | |
events_ = events.loc[molecule] | |
out = events_[['t1']].copy(deep=True) | |
if pt_sl[0] > 0: | |
pt = pt_sl[0] * events_['trgt'] | |
else: | |
pt = pd.Series(index=events.index) # NaNs | |
if pt_sl[1] > 0: | |
sl = -pt_sl[1] * events_['trgt'] | |
else: | |
sl = pd.Series(index=events.index) # NaNs | |
for loc, t1 in events_['t1'].fillna(close.index[-1]).iteritems(): | |
df0 = close[loc:t1] # path prices | |
df0 = (df0 / close[loc] - 1) * events_.at[loc, 'side'] # path returns | |
out.loc[loc, 'sl'] = df0[df0 < sl[loc]].index.min() # earliest stop loss | |
out.loc[loc, 'pt'] = df0[df0 > pt[loc]].index.min() # earliest profit taking | |
return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment