python - 在某些点找到最大值和最小值 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
我toy['inten']
想当max(toy['ret_cum'].iloc[1,4])
循环为 99 时(即 0.067..),然后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
输出 -
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
推荐阅读
- java - Apache POI replaceText() 副作用,改变行距
- excel - 随着行的增加,单元格中的居中形状从顶部增加高度
- swift - 我应该如何将 DispatchGroup 用于两个 url 请求?
- javascript - 如何在javascript中的两个现有对象之间复制
- z3 - 当断言 0 除以 0 为 1 时,z3 返回未知
- python-3.x - 人脸识别库
- c# - OnTriggerEnter 触发太晚了
- python - 用于提取占位符匹配的 RegEx
- excel - 通过 cmd 运行 excel 宏
- android - 如何设置 EditText 菜单项的文本?