为了账号安全,请及时绑定邮箱和手机立即绑定

在 Pandas 中找到当前和先前移动平均线交叉之间的最小值

在 Pandas 中找到当前和先前移动平均线交叉之间的最小值

狐的传说 2021-10-12 17:22:04
我有一个包含股票价格数据的大型数据框 df.columns = ['open','high','low','close']问题定义:当 EMA 交叉发生时,我提到 df['cross'] = cross。每次发生交叉时,如果我们将当前交叉标记为 crossover4,我想检查交叉 3 和交叉 4 之间 df['low'] 的最小值是否大于交叉 1 之间的 df['low'] 最小值和 2. 我已经根据迄今为止从“Gherka”收到的帮助尝试编写代码。我已经索引了交叉并找到了连续交叉之间的最小值。因此,每次发生交叉时,都必须与前 3 次交叉进行比较,我需要检查 MIN(CROSS4,CROSS 3) > MIN(CROSS2,CROSS1)。如果你们能帮我完成,我将不胜感激。import pandas as pd    import numpy as np    import bisect as bsdata = pd.read_csv("Nifty.csv")    df = pd.DataFrame(data)    df['5EMA'] = df['Close'].ewm(span=5).mean()    df['10EMA'] = df['Close'].ewm(span=10).mean()    condition1 = df['5EMA'].shift(1) < df['10EMA'].shift(1)    condition2 = df['5EMA'] > df['10EMA']    df['cross'] = np.where(condition1 & condition2, 'cross', None)    cross_index_array = df.loc[df['cross'] == 'cross'].indexdef find_index(a, x):        i = bs.bisect_left(a, x)        return a[i-1]def min_value(x):    """Find the minimum value of 'Low' between crossovers 1 and 2, crossovers 3 and 4, etc..."""        cur_index = x.name        prev_cross_index = find_index(cross_index_array, cur_index)        return df.loc[prev_cross_index:cur_index, 'Low'].min()df['min'] = None    df['min'][df['cross'] == 'cross'] = df.apply(min_value, axis=1)    print(df)
查看完整描述

1 回答

?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

这应该可以解决问题:


import pandas as pd


df = pd.DataFrame({'open': [1, 2, 3, 4, 5],

                   'high': [5, 6, 6, 5, 7],

                   'low': [1, 3, 3, 4, 4],

                   'close': [3, 5, 3, 5, 6]})


df['day'] = df.apply(lambda x: 'bull' if (

    x['close'] > x['open']) else None, axis=1)


df['min'] = None

df['min'][df['day'] == 'bull'] = pd.rolling_min(

    df['low'][df['day'] == 'bull'], window=2)


print(df)


#    close  high  low  open   day   min

# 0      3     5    1     1  bull   NaN 

# 1      5     6    3     2  bull     1

# 2      3     6    3     3  None  None

# 3      5     5    4     4  bull     3

# 4      6     7    4     5  bull     4

开放评论!


查看完整回答
反对 回复 2021-10-12
  • 1 回答
  • 0 关注
  • 196 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号