在某些点上寻找最大值和最小值

2024-06-26 00:24:02 发布

您现在位置:Python中文网/ 问答频道 /正文

鉴于以下情况:

 toy = pd.DataFrame({
                'price': [100, 103, 107, 105, 99, 96, 98, 103],
                'barrier': [102, 102, 102,102,102,102, 102, 102],
                'date': ['2020-02-28', '2020-03-01', '2020-03-02','2020-03-03', '2020-03-04', '2020- 
                          03-05', '2020-03-06', '2020-03-07']})

toy['date'] = pd.to_datetime(toy['date']) #just make datetime obj
toy['rets'] = np.log(toy['price']/toy['price'].shift(1))
toy['ret_cum'] = toy['rets'].cumsum()
toy['loop'] = [0, 103, 0, 0, 99, 0, 0, 103] #some signal
toy['inten'] = 0.0 #initialize

我希望toy['inten']在循环为99时为max(toy['ret_cum'].iloc[1,4])(即0.067..),然后在循环为103时为min(toy['ret_cum'].iloc[5,7])(即-0.0408),依此类推

更一般地说,np.where(toy['loop'] != 0)产生(1,4,7)…我想检查在间隔1到4,然后是5到7之间达到的最大水平,以此类推

enter image description here


Tags: loopdataframedatetimedatenp情况pricepd
1条回答
网友
1楼 · 发布于 2024-06-26 00:24:02

好吧,这可能有用。它在最小值和最大值之间交替,因为没有提供其背后的特定标准

start = -1
stop = -1
count = 0
for i in toy.index:
    if stop > max(toy.index):
        break
    if toy.loc[i, "loop"] != 0:
        if count == 0:
            start = i
        else:
            stop = i
            if count % 2 == 0:
                toy.loc[i, "inten"] = toy.loc[start:stop, "ret_cum"].min()
            else:
                toy.loc[i, "inten"] = toy.loc[start:stop, "ret_cum"].max()
            start = stop + 1
        count += 1

输出-

   price  barrier       date      rets   ret_cum  loop     inten
0    100      102 2020-02-28       NaN       NaN     0  0.000000
1    103      102 2020-03-01  0.029559  0.029559   103  0.000000
2    107      102 2020-03-02  0.038100  0.067659     0  0.000000
3    105      102 2020-03-03 -0.018868  0.048790     0  0.000000
4     99      102 2020-03-04 -0.058841 -0.010050    99  0.067659
5     96      102 2020-03-05 -0.030772 -0.040822     0  0.000000
6     98      102 2020-03-06  0.020619 -0.020203     0  0.000000
7    103      102 2020-03-07  0.049762  0.029559   103 -0.040822

相关问题 更多 >