繁体   English   中英

在某些点找到最大值和最小值 Pandas Python

[英]Finding maxima and minima at certain points Pandas 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

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

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

在此处输入图像描述

好的,这可能有效。 它在 min 和 max 之间交替,因为没有提供其背后的特定标准。

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

Output -

   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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM