# import packages, seed numpy
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.seed=42
生成模拟数据
时间戳和价格数据列表:
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})
寻找低点
让我们定义window。每次代码考虑一个数据点时,它都会考虑window-之前的许多数据点(不包括它自己)。
window=3
遍历价格,检查当前价格是否低于window-之前的任何价格。保存 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)
或者,如果您更喜欢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)]
检查结果
让我们plot the data 和我们的发现来确保它是正确的。我们将plot the lows as vertical lines 参与我们的阴谋。
df.plot()
for index in indices:
plt.axvline(index,c='r')
导致:
这是我们所期望的。