问题

我有一个沿着以下行的数据帧,用于分析股票数据:

     timestamp                    Price      Exit Price
1   2019-09-29 15:33:00          14         
2   2019-09-29 15:34:00          15          
3   2019-09-29 15:35:00          14         
4   2019-09-29 15:36:00          17         
5   2019-09-29 15:37:00          20        
 

我正在尝试反向测试策略,所以当满足具有以下任何条件的第一行时,我想用价格列的后续值填充Exit价格列:

  1. 当前行时间戳和比较时间戳之间的时间差大于或等于 X 分钟。
  2. 当前行价和比较行价之间的百分比差异大于Y%

例如,如果分钟数为2,返回率为10%,则表应填充如下:

     timestamp                    Price      Exit Price
1   2019-09-29 15:33:00          14         14<-- From Row 3 because 2 minutes passed
2   2019-09-29 15:34:00          15         17<-- From Row 4, both conditions satisfied
3   2019-09-29 15:35:00          14         17<-- From Row 4, difference greater than 10%
4   2019-09-29 15:36:00          17         20
5   2019-09-29 15:37:00          20         Nan
 

我想过实现类似于这样的解决方案:

 customFilter(row):
    results = df[
                (df['timestamp'] > row['timestamp']) &
                (
                  (df['timestamp'] <= (row['timestamp']+pd.timedelta('2m')) |
                  (df['price'] > row['price']*1.1)
                )
             ]

     if results.shape[0] > 0:
         return results['price'].first()

     return nan

df['Exit Price'] = df.apply(lambda x: customFilter(x), axis = 1)
 

问题是,有没有更好的方法来做到这一点?它似乎不是最有效或最快的方法,特别是如果我增加了我的数据集的大小.

  最佳答案

伊斯兰法院联盟,这是你需要的。

 from datetime import timedelta
df['timestamp'] = pd.to_datetime(df['timestamp'])

E_Price=[]
time_diff = df['timestamp'].apply(lambda x: x >= (df['timestamp']+timedelta(minutes=2)))
price_diff = df['Price'].apply(lambda x: x >= (df['Price']*1.1))
for i in range(len(df)):
    check = (time_diff|price_diff)[i]
    ind = check.idxmax()
    if ind != 0:
        val = df.iloc[ind,1]
    else:
        val = np.nan
    E_Price.append(val)    

df['Exit_Price'] = E_Price
df['Exit_Price'] = df.Exit_Price.astype(pd.Int32Dtype())
print(df)
 

产出

             timestamp   Price   Exit_Price
0   2019-09-29 15:33:00     14  14
1   2019-09-29 15:34:00     15  17
2   2019-09-29 15:35:00     14  17
3   2019-09-29 15:36:00     17  20
4   2019-09-29 15:37:00     20  NaN
 

  相同标签的其他问题

pythonpandas