# import packages, seed numpy
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.seed=42
Generate mock data
Timestamps and price data as list:
timestamps = ['timestamp'+str(x) for x in range(20)]
price = [np.random.normal(100,10) for _ in range(20)]
Put them to a Pandas dataframe:
df = pd.DataFrame({'timestamps':timestamps,'price':price})
Look for lows
Let's define window
. Every time the code considers a datapoint, it will consider window
-many datapoints before it (not including itself).
window=3
Iterate through price, checking if the current price is the lower than any of the window
-many prices before. Save the indices of those datapoints for which this is True
:
indices=[]
for index, row in enumerate(df.iterrows()):
if index >= window:
if all(df.loc[index,'price'] < each for each in df[index-window:index]['price'].values):
indices.append(index)
Or, if you prefer list comprehensions:
indices = [index for index, row in enumerate(df.iterrows()) if index>=window and all(df.loc[index,'price'] < each for each in df[index-window:index]['price'].values)]
Check results
Let's plot the data & our findings to make sure it is right. We will plot the lows as vertical lines on our plot.
df.plot()
for index in indices:
plt.axvline(index,c='r')
Resulting in:

Which is what we have expected.