Skip to content

Instantly share code, notes, and snippets.

@samchaaa
Created January 18, 2021 10:55
Show Gist options
  • Save samchaaa/343b71154a3a1c61c70dc1517a8eeba0 to your computer and use it in GitHub Desktop.
Save samchaaa/343b71154a3a1c61c70dc1517a8eeba0 to your computer and use it in GitHub Desktop.
def get_max_min(prices, smoothing, window_range):
# Get prices
smooth_prices = prices['close'].rolling(window=smoothing).mean().dropna()
# Get max and min for window
local_max = argrelextrema(smooth_prices.values, np.greater)[0]
local_min = argrelextrema(smooth_prices.values, np.less)[0]
print('local_max, local_min', local_max, local_min)
price_local_max_dt = []
# iterate thru points
for i in local_max:
# only check in areas with complete window coverage
if (i>window_range) and (i<len(prices)-window_range):
# append the index of the max for that window (for multiple windows, we'll get the same maxes as they overlap)
price_local_max_dt.append(prices.iloc[i-window_range:i+window_range]['close'].idxmax())
print('idx max', prices.iloc[i-window_range:i+window_range]['close'].idxmax())
price_local_min_dt = []
for i in local_min:
if (i>window_range) and (i<len(prices)-window_range):
price_local_min_dt.append(prices.iloc[i-window_range:i+window_range]['close'].idxmin())
maxima = pd.DataFrame(prices.loc[price_local_max_dt])
minima = pd.DataFrame(prices.loc[price_local_min_dt])
max_min = pd.concat([maxima, minima]).sort_index()
max_min.index.name = 'date'
max_min = max_min.reset_index()
max_min = max_min[~max_min.date.duplicated()]
p = prices.reset_index()
# max_min['day_num'] = p[p['timestamp'].isin(max_min.date)].index.values
# max_min = max_min.set_index('day_num')['close']
return max_min
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment