Skip to content

Commit

Permalink
make previous_high_low function faster
Browse files Browse the repository at this point in the history
  • Loading branch information
joshyattridge committed May 25, 2024
1 parent b0025fc commit 3475f05
Showing 1 changed file with 21 additions and 21 deletions.
42 changes: 21 additions & 21 deletions smartmoneyconcepts/smc.py
Original file line number Diff line number Diff line change
Expand Up @@ -710,32 +710,32 @@ def previous_high_low(cls, ohlc: DataFrame, time_frame: str = "1D") -> Series:
broken_high = np.zeros(len(ohlc), dtype=np.int32)
broken_low = np.zeros(len(ohlc), dtype=np.int32)

resampled_ohlc = ohlc.resample(time_frame).agg(
{
"open": "first",
"high": "max",
"low": "min",
"close": "last",
"volume": "sum",
}
).dropna()

currently_broken_high = False
currently_broken_low = False
last_broken_time = None
for i in range(len(ohlc)):
resampled_ohlc = (
ohlc[:i]
.resample(time_frame)
.agg(
{
"open": "first",
"high": "max",
"low": "min",
"close": "last",
"volume": "sum",
}
)
)
if len(resampled_ohlc) >= 1:
if last_broken_time != resampled_ohlc.index[-1]:
currently_broken_high = False
currently_broken_low = False
last_broken_time = resampled_ohlc.index[-1]
# remove rows with nan values (ignoring weekends)
resampled_ohlc = resampled_ohlc.dropna()
previous_high[i] = resampled_ohlc["high"].iloc[-2] if len(resampled_ohlc) > 1 else np.nan
previous_low[i] = resampled_ohlc["low"].iloc[-2] if len(resampled_ohlc) > 1 else np.nan
resampled_previous_index = np.where(
resampled_ohlc.index < ohlc.index[i]
)[0]
if len(resampled_previous_index) <= 1:
previous_high[i] = np.nan
previous_low[i] = np.nan
continue
resampled_previous_index = resampled_previous_index[-1]

previous_high[i] = resampled_ohlc["high"].iloc[resampled_previous_index]
previous_low[i] = resampled_ohlc["low"].iloc[resampled_previous_index]
currently_broken_high = ohlc["high"].iloc[i] > previous_high[i] or currently_broken_high
currently_broken_low = ohlc["low"].iloc[i] < previous_low[i] or currently_broken_low
broken_high[i] = 1 if currently_broken_high else 0
Expand Down

0 comments on commit 3475f05

Please sign in to comment.