如何在pandas中使用带移位功能的min/max?
How to use min/max with shift function in pandas?
我有时间序列数据 (euro/usd)。
我想创建条件为
的新列
(阅读我的代码更容易理解条件。)
如果 3 个先前的最高价中的最小值小于或等于当前价格,则它将是 'BUY_SIGNAL',如果先前的 3 个最低价中的最大值高于或等于当前价格,则它将是 'SELL_SIGNAL'。
这是我的table样子
DATE OPEN HIGH LOW CLOSE
0 1990.09.28 1.25260 1.25430 1.24680 1.24890
1 1990.10.01 1.25170 1.26500 1.25170 1.25480
2 1990.10.02 1.25520 1.26390 1.25240 1.26330
3 1990.10.03 1.26350 1.27000 1.26030 1.26840
4 1990.10.04 1.26810 1.27750 1.26710 1.27590
这是我的代码(我尝试创建 2 个函数但它不起作用)
def target_label(df):
if df['HIGH']>=[df['HIGH'].shift(1),df['HIGH'].shift(2),df['HIGH'].shift(3)].min(axis=1):
return 'BUY_SIGNAL'
if df['LOW']>=[df['LOW'].shift(1),df['LOW'].shift(2),df['LOW'].shift(3)].min(axis=1):
return 'SELL_SIGNAL'
else:
return 'NO_SIGNAL'
def target_label(df):
if df['HIGH']>=df[['HIGH1','HIGH2','HIGH3'].min(axis=1):
return 'BUY_SIGNAL'
if df['LOW']<=df[['LOW1','LOW2','LOW3']].max(axis=1):
return 'SELL_SIGNAL'
else:
return 'NO_SIGNAL'
d_df.apply (lambda df: target_label(df), axis=1)
您可以使用 rolling(3).min()
获取前 3 行中的最小值。这同样适用于 max
、mean
等其他函数。类似于以下内容:
df['signal'] = np.where(
df['HIGH'] >= df.shift(1).rolling(3)['HIGH'].min(), 'BUY_SIGNAL',
np.where(
df['LOW'] >= df.shift(1).rolling(3)['LOW'].min(), 'SELL_SIGNAL',
'NO_SIGNAL'
)
)
我有时间序列数据 (euro/usd)。 我想创建条件为
的新列(阅读我的代码更容易理解条件。) 如果 3 个先前的最高价中的最小值小于或等于当前价格,则它将是 'BUY_SIGNAL',如果先前的 3 个最低价中的最大值高于或等于当前价格,则它将是 'SELL_SIGNAL'。
这是我的table样子
DATE OPEN HIGH LOW CLOSE
0 1990.09.28 1.25260 1.25430 1.24680 1.24890
1 1990.10.01 1.25170 1.26500 1.25170 1.25480
2 1990.10.02 1.25520 1.26390 1.25240 1.26330
3 1990.10.03 1.26350 1.27000 1.26030 1.26840
4 1990.10.04 1.26810 1.27750 1.26710 1.27590
这是我的代码(我尝试创建 2 个函数但它不起作用)
def target_label(df):
if df['HIGH']>=[df['HIGH'].shift(1),df['HIGH'].shift(2),df['HIGH'].shift(3)].min(axis=1):
return 'BUY_SIGNAL'
if df['LOW']>=[df['LOW'].shift(1),df['LOW'].shift(2),df['LOW'].shift(3)].min(axis=1):
return 'SELL_SIGNAL'
else:
return 'NO_SIGNAL'
def target_label(df):
if df['HIGH']>=df[['HIGH1','HIGH2','HIGH3'].min(axis=1):
return 'BUY_SIGNAL'
if df['LOW']<=df[['LOW1','LOW2','LOW3']].max(axis=1):
return 'SELL_SIGNAL'
else:
return 'NO_SIGNAL'
d_df.apply (lambda df: target_label(df), axis=1)
您可以使用 rolling(3).min()
获取前 3 行中的最小值。这同样适用于 max
、mean
等其他函数。类似于以下内容:
df['signal'] = np.where(
df['HIGH'] >= df.shift(1).rolling(3)['HIGH'].min(), 'BUY_SIGNAL',
np.where(
df['LOW'] >= df.shift(1).rolling(3)['LOW'].min(), 'SELL_SIGNAL',
'NO_SIGNAL'
)
)