我有一个OHLC数据框架,例如:
<表类>
指数
打开
关闭高低 tbody><<tr>2021-03-23 10:00:00 + 0 1421.100 1424.500 1427.720 1422.650 2021-03-23 11:00:00 + 0 1424.500 1421.480 1422.400 1411.890 2021-03-23 12:00:00 + 0 1421.480 1435.170 1443.980 1433.780 2021-03-23 13:00:00 + 0 1435.170 1440.860 1443.190 1437.590 2021-03-23 14:00:00 + 0 1440.860 1438.920 1443.570 1435.200 2021-03-23 15:00:00 + 0 1438.920 1435.990 1444.840 1435.060 2021-03-23 16:00:00 + 0 1435.990 1441.920 1446.610 1441.450 表类>
我认为最好的方法和你现在的做法没有太大的不同:
from datetime import timedelta
def check(x, change=0.01):
time = x.name
price = ohlc.loc[time, 'close']
while True:
if time not in ohlc.index: # If we reach the end
return 0
high = ohlc.loc[time, 'high']
low = ohlc.loc[time, 'low']
if high > (1.0 + change) * price: # Upper thresh broken
return 1
elif low < 1.0 - change) * price: # Lower thresh broken
return -1
time = time + timedelta(hours=1) # Time update
ohlc['check'] = ohlc.apply(check, axis=1)
如果您担心的是效率,那么使用这种方法会稍微更有效率一些,因为它只会在需要突破阈值时向前看。或者,您可以修改while循环,将其限制为100小时,将每行检查的次数限制为100次:
endtime = time + timedelta(hours=100)
while time < endtime:
# etc