我有一個沿著以下行的資料幀,用於分析股票資料:
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價格列:
- 當前行時間戳和比較時間戳之間的時間差大於或等於 X 分鐘。
- 當前行價和比較行價之間的百分比差異大於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)
問題是,有沒有更好的方法來做到這一點?它似乎不是最有效或最快的方法,特別是如果我增加了我的資料集的大小.