猿问

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

我有一个包含股票价格数据的大型数据框 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 bs


data = 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'].index


def 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)


狐的传说
浏览 197回答 1
1回答

拉风的咖菲猫

这应该可以解决问题:import pandas as pddf = pd.DataFrame({'open': [1, 2, 3, 4, 5],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'high': [5, 6, 6, 5, 7],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'low': [1, 3, 3, 4, 4],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'close': [3, 5, 3, 5, 6]})df['day'] = df.apply(lambda x: 'bull' if (&nbsp; &nbsp; x['close'] > x['open']) else None, axis=1)df['min'] = Nonedf['min'][df['day'] == 'bull'] = pd.rolling_min(&nbsp; &nbsp; df['low'][df['day'] == 'bull'], window=2)print(df)#&nbsp; &nbsp; close&nbsp; high&nbsp; low&nbsp; open&nbsp; &nbsp;day&nbsp; &nbsp;min# 0&nbsp; &nbsp; &nbsp; 3&nbsp; &nbsp; &nbsp;5&nbsp; &nbsp; 1&nbsp; &nbsp; &nbsp;1&nbsp; bull&nbsp; &nbsp;NaN&nbsp;# 1&nbsp; &nbsp; &nbsp; 5&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; 3&nbsp; &nbsp; &nbsp;2&nbsp; bull&nbsp; &nbsp; &nbsp;1# 2&nbsp; &nbsp; &nbsp; 3&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; 3&nbsp; &nbsp; &nbsp;3&nbsp; None&nbsp; None# 3&nbsp; &nbsp; &nbsp; 5&nbsp; &nbsp; &nbsp;5&nbsp; &nbsp; 4&nbsp; &nbsp; &nbsp;4&nbsp; bull&nbsp; &nbsp; &nbsp;3# 4&nbsp; &nbsp; &nbsp; 6&nbsp; &nbsp; &nbsp;7&nbsp; &nbsp; 4&nbsp; &nbsp; &nbsp;5&nbsp; bull&nbsp; &nbsp; &nbsp;4开放评论!
随时随地看视频慕课网APP

相关分类

Python
我要回答